2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScript 特定桁の0と1で表すことができる全ての組み合わせを求める関数

Last updated at Posted at 2020-11-04

やりたいこと

例: 引数1に3を渡すと3ビットで表せれるすべての組み合わせを出力する。
たまに使用するので、個人的なメモ(誰かの役に立つと嬉しい)

出力例

[
  [ '0', '0', '0' ],
  [ '0', '0', '1' ],
  [ '0', '1', '0' ],
  [ '0', '1', '1' ],
  [ '1', '0', '0' ],
  [ '1', '0', '1' ],
  [ '1', '1', '0' ],
  [ '1', '1', '1' ]
]

コード

const getAllBit = (len) => {
  //すべての組み合わせの個数
  const end = Math.pow(2, len) - 1

  let result = []
  for (let i = 0; i <= end; i++) {
    //toStringの引数に2を渡すことで2進数表記にする
    //len分だけ0うめ
    const bit = i.toString(2).padStart(len, '0')
    result.push(bit.split(''))
  }

  return result
}

console.log(getAllBit(5))

追記: コメント欄でご指摘があった、再利用しない関数をなくし一つの関数でまとめました。

実行例

引数に5を渡した場合(上記のコードと同じ)

[
  [ '0', '0', '0', '0', '0' ],
  [ '0', '0', '0', '0', '1' ],
  [ '0', '0', '0', '1', '0' ],
  [ '0', '0', '0', '1', '1' ],
  [ '0', '0', '1', '0', '0' ],
  [ '0', '0', '1', '0', '1' ],
  [ '0', '0', '1', '1', '0' ],
  [ '0', '0', '1', '1', '1' ],
  [ '0', '1', '0', '0', '0' ],
  [ '0', '1', '0', '0', '1' ],
  [ '0', '1', '0', '1', '0' ],
  [ '0', '1', '0', '1', '1' ],
  [ '0', '1', '1', '0', '0' ],
  [ '0', '1', '1', '0', '1' ],
  [ '0', '1', '1', '1', '0' ],
  [ '0', '1', '1', '1', '1' ],
  [ '1', '0', '0', '0', '0' ],
  [ '1', '0', '0', '0', '1' ],
  [ '1', '0', '0', '1', '0' ],
  [ '1', '0', '0', '1', '1' ],
  [ '1', '0', '1', '0', '0' ],
  [ '1', '0', '1', '0', '1' ],
  [ '1', '0', '1', '1', '0' ],
  [ '1', '0', '1', '1', '1' ],
  [ '1', '1', '0', '0', '0' ],
  [ '1', '1', '0', '0', '1' ],
  [ '1', '1', '0', '1', '0' ],
  [ '1', '1', '0', '1', '1' ],
  [ '1', '1', '1', '0', '0' ],
  [ '1', '1', '1', '0', '1' ],
  [ '1', '1', '1', '1', '0' ],
  [ '1', '1', '1', '1', '1' ]
]

5ビットで表すことができるすべての組み合わせが出力できてます。

参考にした記事

js 与えられた整数を二進数で返す

2
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?