Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8829

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

$
0
0

やりたいこと

例:引数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' ]
]

コード

constgetAllBit=(len)=>{//すべての組み合わせの個数constend=Math.pow(2,len)-1letresult=[]for(leti=0;i<=end;i++){//len分だけ0うめconstbit=toBinary(i).toString().padStart(len,'0')result.push(bit.split(''))}returnresult}consttoBinary=(n)=>parseInt(n.toString(2))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 与えられた整数を二進数で返す


Viewing all articles
Browse latest Browse all 8829

Trending Articles