I am trying to create all possible combinations for pair 1 within a given width.
Let's say the bit width is 6, that is, number 32. This is what I would like to generate:
000000 000011 000110 001100 001111 011000 011011 011110 110000 110011 110110 111100 111111
If I have variables:
var a = 1, b = 2; num = a | b;
and create a loop in which I will cyclically switch to width - 1 time, and when I shift both a << 1 and b << 1 , I will get all the combinations for one pair. After that, I got pretty stuck.
Can someone please provide some help.
Update: working example
Based on Barmar's mathematical approach, I managed to implement
var arr = [], arrBits = []; function getCombs(pairs, startIdx) { var i, j, val = 0, tmpVal, idx; if (startIdx + 2 < pairs) { startIdx = arr.length - 1; pairs -= 1; } if (pairs < 2) { return; } for (i = 0; i < pairs-1; i++) { idx = startIdx - (i * 2); val += arr[idx]; } for (j = 0; j < idx - 1; j++) { arrBits.push((val + arr[j]).toString(2)); } getCombs(pairs, startIdx-1); } (function initArr(bits) { var i, val, pairs, startIdx; for (i = 1; i < bits; i++) { val = i == 1 ? 3 : val * 2; arr.push(val); arrBits.push(val.toString(2)); } pairs = Math.floor(bits / 2); startIdx = arr.length - 1; getCombs(pairs, startIdx); console.log(arrBits); }(9));
Working example on JSFiddle
http://jsfiddle.net/zywc5/