So I understand that my question is about masking. I saw the documentation of masking for javascript here.
so I tried:
var PEN = 1;
var CHAIR = 2;
var TABLE = 4;
> PEN | CHAIR
3
But what if what I have is 3 how do I get what I have from that number alone?
Original Question
Say, I have the following constant numbers:
1 | 2 | 4
These numbers corresponds to a something.
Let us say: 1 is a pen, 2 is a chair and 4 is a table.
Possibilities:
If I have the #1 it means I have a pen but NO chair and table.
If I have the #2 it means I have a chair but NO pen and table.
If I have the #4 it means I have a table but NO pen and chair.
If I have the #3 it means I have a pen and a chair but NO table.
If I have the #6 it means I have a chair, a table but NO pen.
If I have the #7 it means I have a pen, a chair and a table.
Question: Now say all I know about is the number 6. How do I programatically decipher that 6 means 2 and 4 or I have a chair and a table?
Sorry, this is also confusing me. I'm trying to reimplement a skills list algorithm for a game to javascript. Where if I have 6 it means I have the 2nd and 3rd skill but not the 1st skill.
Also what is this approach called?
Lets say you have 5 skills... A, B, C, D and E. You can encode these skills as first, second, third, fourth and fifth bit of an integer.
So, if a players skill is 0b00001000... that means he has 4th skill.
Now,
// No skill
var skill = 0;
// add skill B... which means set second bit to 1.
skill = skill | ( 1 << 1 );
// add skill A
skill = skill | ( 1 << 0 );
//check for skill B,
var hasSkillB = ( ( skill & ( 1 << 1 ) ) > 0 );
// Remove skill B
skill = skill & ( ~( 1 << 1 ) );
This looks more like a problem of finding elements summing up to the target value:
var elementsUsedInSum = function (arr, sum) {
var curr_sum = arr[0], start = 0, i;
for (i = 1; i <= arr.length; i++)
{
while (curr_sum > sum && start < i-1)
{
curr_sum = curr_sum - arr[start];
start += 1;
}
if (curr_sum === sum)
{
console.log ("Elements from " + start + " to " + i-1 + " found.");
}
// Add this element to curr_sum
if (i < n)
curr_sum = curr_sum + arr[i];
}
console.log ("Combination not possible");
}
If you want an easy way to do it just mask the bits and compare it with the number:
var FLAG_A = 1; // 0001 - PEN
var FLAG_B = 2; // 0010 - CHAIR
var FLAG_C = 4; // 0100 - TABLE
var PEN;
var CHAIR;
var TABLE;
n = 3; //Input number
if (n & FLAG_A) {
PEN = true;
} else {
PEN = false;
}
if (n & FLAG_B) {
CHAIR = true;
} else {
CHAIR = false;
}
if (n & FLAG_C) {
TABLE = true;
} else {
TABLE = false;
}
Related
I am a math teacher a need a way to create word problems and test students on those problems. Because i want to be able to retest these students i needed a way to recreate the same question and display answer choices that would be different each time based on the problem given. So i used arrays to hold variable information like names locations or foods that come up in the word problem.
Ex dave has 1 apple on monday. Dave goes to the store and gets 3 more apples. How many apples does dave have?
So currently i am able to create a name array, fruit array, location array to replace the (name fruit or location) each time the question is ask.
My issue is how do i add fractions to both the answers and the possible choices?. My second issue is i need a way to provide numbers and words in the answer. I have attached the example of questions i am trying to create.
Currently i have multiple choice and open end answers that work based on adding a random amount to the actual answer.
enter image description here
sry, but your code is so awfully cluttered and redundant, I didn't want to dir through all that.
So I made a simple example that generates "random" sentences by utilizing a PRNG (Mersenne Twister)
//I'll add the non minified version
prng=function(){"use strict"
function n(r,t){function e(){var n=r,e=t,u=n[e],o=n[t=623>e?e+1:0],i=n[227>e?e+397:e-227]
return n[e]=i^(2147483648&u|2147483647&o)>>>1^(1&o&&2567483615),u^=u>>>11,u^=u<<7&2636928640,u^=u<<15&4022730752,u^=u>>>18,u>>>0}var u={uint32:e,float(){return e()/4294967296},double(){return(e()>>>6)/67108864+(e()>>>5)/9007199254740992},seed(n){var e=n>>>0||5489,o=1
for(r[0]=e,t=0;624>o;++o)e^=e>>>30,e=(r[o]=(1812433253*(e>>>16)<<16)+1812433253*(65535&e)+o)>>>0
return u},clone(){return n(new Uint32Array(r),t)}}
return u}return n(new Uint32Array(624),0).seed(4294967296*Math.random()).clone}()
//the actual application
var target = document.querySelector('#sentences');
var seed = document.querySelector('#seed');
var numRows = document.querySelector('#numRows');
seed.onchange = numRows.onchange = update;
const protagonists = ['Beth', 'Chris', 'Carl', 'April', 'Cinnamon','Ethan', 'Sammy', 'Dan', 'Devron', 'Livron', 'Paul', 'the Frog', 'the Dog', 'the Hamster'];
const actions = ['saw', 'walked to', 'jumped onto', 'hit', 'got bitten by', 'kissed'];
//create a new prng
var random = prng();
//a utility
function sample(array){
return array[ Math.floor(random.float() * array.length) ];
}
function update(){
//re-seed the prng
random.seed(+seed.value);
//flush the seeded values out of the buffer
for(var i=1234; i--; random.float());
var rows = Array(+numRows.value);
for(var i = 0; i<rows.length; ++i){
var a = sample(protagonists),
b = sample(protagonists),
action = sample(actions);
while(a === b) b = sample(protagonists);
rows[i] = `<li>${a} ${action} ${b}</li>`;
}
target.innerHTML = `<ul>${ rows.join("\n") }</ul>`;
}
update();
<label>
Seed for the PRNG:
<input id="seed" type="number" min=0 step=1 value="42"/>
</label>
<br>
<label>
number of generated rows:
<input id="numRows" type="number" min=0 step=1 value="5"/>
</label>
<div id="sentences"></div>
Play a bit with the inputs. The point of this example is to show how this prng always generates the same "random" expresions for the same seed.
If you check out the code, yuu'll see that id doesn't cache any sentences or so, they are generated from scratch each time you change one of the inputs.
And the not-minified version of the prng:
prng = (function(){
'use strict';
//implementing a mersenne-twister with 32bit
function _mt19937(buffer, i){
function uint32() {
var $ = buffer,
j = i,
a = $[j],
b = $[i = j<623? j+1: 0],
c = $[j<227? j+397: j-227];
$[j] = c ^ ((0x80000000 & a | 0x7FFFFFFF & b) >>> 1) ^ (b&1 && 0x9908b0df);
a ^= a >>> 11;
a ^= (a << 7) & 0x9d2c5680;
a ^= (a << 15) & 0xefc60000;
a ^= a >>> 18;
return a >>> 0;
}
var me = {
//0 <= uint32() < 4294967296
uint32,
//0 <= float() < 1 with 32bit precision
float(){
return uint32() / 4294967296;
},
//0 <= double() < 1 with 53bit precision (throwing 11 bit away)
double(){
return (uint32()>>>6) / 67108864 + (uint32()>>>5) / 9007199254740992;
},
//(re-)seed the internal state
seed(seed){
var a = seed>>>0 || 5489, j = 1;
for(buffer[0] = a, i = 0; j<624; ++j){
a ^= a>>>30;
a = (buffer[j] = ((0x6c078965 * (a >>> 16)) << 16) + 0x6c078965 * (0xffff & a) + j)>>>0;
}
return me;
},
//create a new instance that has the same state.
//states are not shared, they develop individually
clone(){
return _mt19937(new Uint32Array(buffer), i);
//return _mt19937(buffer.slice(), i);
}
}
return me;
}
//create a prototype, seed it with a random number (per page and request)
//each generated instance will start as a clone of this,
//and return the same sequence
//unless you (re-)seed them
return _mt19937(new Uint32Array(624),0).seed( Math.random() * 4294967296 ).clone;
//return _mt19937(new Array(624),0).seed( Math.random() * 4294967296 ).clone;
})();
Like the picture above, how would it be possible to create four separate lines of text, given the word defendtheeastwallofthecastle while using Javascript?
Math solution
Take a closer look at your output:
a.....g.....m.....s.
.b...f.h...l.n...r.t
..c.e...i.k...o.q...
...d.....j.....p....
Note that it can be splitted into similiar repeating blocks:
a..... g..... m..... s.
.b...f .h...l .n...r .t
..c.e. ..i.k. ..o.q. ..
...d.. ...j.. ...p.. ..
The length of this blocks is calculable: every row, except for the first one and the last one, has 2 letters. The total length will be: rows * 2 - 2. Let's call it blockLength. By the way, x * 2 - 2 is always even - it is important.
Now, you can see that in every block the letters are "sinking" in the left half, and arising in the second one. So, if you make some observations and analysis, you will understand that for blockLength == 6 you need to output letters at i:
row | i % blockLength
----------------------------
0 | 0
1 | 1, blockLength - 1
2 | 2, blockLength - 2
3 | 3
After i exceeds blockLength, it will repeat again and again, until the end of the string. This regularity can be easily converted to a JavaScript loop, if you know its basics.
Lazy solution
Within a loop set values in zig-zag order:
var str = 'abcdefghijklmopqrst';
var rows = 4, letterRows = [], currentRow = 0, direction = 1;
for (var i = 0; i < str.length; i++)
{
letterRows.push(currentRow);
currentRow += direction;
if ((direction === 1 && currentRow == rows - 1) // bottom limit
|| (direction === -1 && currentRow == 0)) // top limit
{
direction = direction * -1; // invert direction
}
}
Then, within nested loops simply output your letters according to letterRows:
for (var row = 0; row < rows; row++)
{
for (var i = 0; i < str.length; i++)
{
output(letterRows[i] == row ? str[i] : '.'); // output is any possible output in your case
}
output('\n');
}
I'm presented with the following challenge question:
There are a circle of 100 baskets in a room; the baskets are numbered
in sequence from 1 to 100 and each basket contains one apple.
Eventually, the apple in basket 1 will be removed but the apple in
basket 2 will be skipped. Then the apple in basket 3 will be removed.
This will continue (moving around the circle, removing an apple from a
basket, skipping the next) until only one apple in a basket remains.
Write some code to determine in which basket the remaining apple is
in.
I concluded that basket 100 will contain the last apple and here's my code:
var allApples = [];
var apples = [];
var j = 0;
var max = 100;
var o ='';
while (j < max) {
o += ++j;
allApples.push(j);
}
var apples = allApples.filter(function(val) {
return 0 == val % 2;
});
while (apples.length > 1) {
for (i = 0; i < apples.length; i += 2) {
apples.splice(i, 1);
}
}
console.log(apples);
My question is: did I do this correctly? What concerns me is the description of "a circle" of baskets. I'm not sure this is relevant at all to how I code my solution. And would the basket in which the remaining apple reside be one that would otherwise be skipped?
I hope someone can let me know if I answered this correctly, answered it partially correct or my answer is entirely wrong. Thanks for the help.
So, ... I got WAY too into this question :)
I broke out the input/output of my last answer and that revealed a pretty simple pattern.
Basically, if the total number of items is a power of 2, then it will be the last item. An additional item after that will make the second item the last item. Each additional item after that will increase the last item by 2, until you reach another item count that is again divisible by a power of 2. Rinse and repeat.
Still not a one-liner, but will be much faster than my previous answer. This will not work for 1 item.
var items = 100;
function greatestPowDivisor(n, p) {
var i = 1;
while(n - Math.pow(p, i) > 0) {
i++;
}
return Math.pow(p, (i - 1));
}
var d = greatestPowDivisor(items, 2)
var last_item = (items - d) * 2;
I believe Colin DeClue is right that there is a single statement that will solve this pattern. I would be really interested to know that answer.
Here is my brute force solution. Instead of moving items ("apples") from their original container ("basket") into a discard pile, I am simply changing the container values from true or false to indicate that an item is no longer present.
var items = 100;
var containers = [];
// Just building the array of containers
for(i=0; i<items; i++) {
containers.push(true);
}
// count all containers with value of true
function countItemsLeft(containers) {
total = 0;
for(i=0; i<containers.length; i++) {
if(containers[i]) {
total++;
}
}
return total;
}
// what is the index of the first container
// with a value of true - hopefully there's only one
function getLastItem(containers) {
for(i=0; i<containers.length; i++) {
if(containers[i]) {
return(i);
}
}
// shouldn't get here if the while loop did it's job
return false;
}
var skip = false;
// loop through the items,
// setting every other to false,
// until there is only 1 left
while(countItemsLeft(containers) > 1) {
for(i=0; i<containers.length; i++) {
if(containers[i]) {
if(skip) {
skip = false;
} else {
containers[i] = false;
skip = true;
}
}
}
}
// what's the last item? add one to account for 0 index
// to get a human readable answer
var last_item = getLastItem(containers) + 1;
Needs error checking, etc... but it should get the job done assuming items is an integer.
I'm new to JavaScript and I am trying to write a simple script that solves linear equations. So far my script solves linear equations that are plus and minus only such as "2x + 28 - 18x = 36 - 4x + 10". I want it to also be able to solve linear equations/algebra problems that contain multiplication and division such as "2x * 3x = 4 / 2x".
I kind of have an idea of what to do next but I think the script I have right now maybe overly complex and it's only going to make it more complicated to add the multiplication and division.
Below is my script. I'm hoping for a few pointers on how I could improve and simplify what I already have and what the best way to add multiplication and division?
My script on JS Bin: http://jsbin.com/ufekug/1/edit
My script:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Problem Solver</title>
<script>
window.onload = function() {
// Total Xs on each side of equation
// Example problem: 5x + 2 = 10 - 2x
var leftSideXTotal = 0; // 5
var rightSideXTotal = 0; // -2
// Total integers on each side of equation
// Example problem: 5x + 2 = 10 - 2x
var leftSideIntTotal = 0; // 2
var rightSideIntTotal = 0; // 10
// Enter a math problem to solve
var problem = "5x + 2 = 10 - 2x";
// Remove all spaces in problem
// Example problem: 5x + 2 = 10 - 2x
problem = problem.replace(/\s/g,''); // 5x+2=10-2x
// Add + signs in front of all - signs
// Example problem: 5x + 2 = 10 - 2x
problem = problem.replace(/-/gi, "+-"); // 5x+2=10+-2x
// Split problem into left and right sides
// Example problem: 5x + 2 = 10 - 2x
var problemArray = problem.split("=");
var problemLeftSide = problemArray[0]; // 5x+2
var problemRightSide = problemArray[1]; // 10+-2x
// Split values on each side into an array
var problemLeftSideValues = problemLeftSide.split("+");
var problemRightSideValues = problemRightSide.split("+");
// Go through the left side values and add them up
for (var i = 0; i < problemLeftSideValues.length; i++) {
// Current value
var currentValue = problemLeftSideValues[i];
// Length of current value
var currentValueLength = currentValue.length;
if (currentValue.charAt(currentValueLength - 1) == "x") { //Check if current value is a X value
// Remove X from end of current value
currentValue = currentValue.split("x");
// Add to total Xs on left side
leftSideXTotal = Number(leftSideXTotal) + Number(currentValue[0]);
} else {
// Add to total integers on left side
leftSideIntTotal = Number(leftSideIntTotal) + Number(problemLeftSideValues[i]);
}
}
// Go through the right side values and add them up
for (var i = 0; i < problemRightSideValues.length; i++) {
// Current value
var currentValue = problemRightSideValues[i];
// Length of current value
var currentValueLength = currentValue.length;
if (currentValue.charAt(currentValueLength - 1) == "x") { //Check if current value is a X value
// Remove X from end of current value
currentValue = currentValue.split("x");
// Add to total Xs on right side
rightSideXTotal = Number(rightSideXTotal) + Number(currentValue[0]);
} else {
// Add to total integers on right side
rightSideIntTotal = Number(rightSideIntTotal) + Number(problemRightSideValues[i]);
}
}
// Compute
var totalXs = (leftSideXTotal - rightSideXTotal)
var totalIntegers = (rightSideIntTotal - leftSideIntTotal)
var solution = (totalIntegers / totalXs)
// Display solution
document.getElementById("divSolution").innerText = solution;
}
</script>
</head>
<body>
<div id="divSolution"></div>
</body>
</html>
You need to write (or use) an operator-precedence parser.
The idea is to turn the equation into a tree, e.g.
x + 3 = 3x - 2
Is really the structure
=
/ \
+ -
/ \ / \
x 3 * 2
/ \
3 x
Where each operator describes an operation between two "branches" of the tree. Using a javascript object it shouldn't be difficult to create the structure:
function tree(lterm,op,rterm) {
t.operator = op;
t.left = lterm;
t.right = rterm;
return t;
}
expression = tree("x", "/", tree("x","+",3) ); // x / (x+3)
Then by manipulating the tree you can resolve the equation, or carry out calculations. To evaluate an expression (with no unknowns), you run through the tree starting at the terminals, and upwards from intersection to intersection. You can replace a section of the tree with a result, or annotate it with a result - add a result variable to the tree object.
Here are some useful methods to include in a tree class:
getLeft
getRight
prettyPrint
evaluate
evaluate("x",5) // x=5, now evaluate
...
It's not just linear operations that can be "parsed" this way. Better parsers will have a list of operators that includes =*/+- but also unary operators: - ( ) sin cos...
I haven't used an operator-precedence parser in javascript, but some must exist prewritten. Surely a kind soul on this site will add a good link or two to my answer.
BTW, the tree approach has many applications. In a spreadsheet:
A2 = A1+B1
In a boolean solver:
A = not (B or C)
C = true
In XML parsing:
<main>
<part>A</part>
<part>B</part>
</main>
I have defined two functions:
getTotalX() : It will give you the count of x for any input string.
getTotalScalars() : It will give you the total of scalars (numbers).
And finally, your updated code (it still does only addition and subtraction):
<script>
window.onload = function() {
// Total Xs on each side of equation
// Example problem: 5x + 2 = 10 - 2x
var leftSideXTotal = 0; // 5
var rightSideXTotal = 0; // -2
// Total integers on each side of equation
// Example problem: 5x + 2 = 10 - 2x
var leftSideIntTotal = 0; // 2
var rightSideIntTotal = 0; // 10
// Enter a math problem to solve
var problem = "5x + 2 = 10 - 2x";
// Remove all spaces in problem
// Example problem: 5x + 2 = 10 - 2x
problem = problem.replace(/\s/g,''); // 5x+2=10-2x
// Add + signs in front of all - signs
// Example problem: 5x + 2 = 10 - 2x
problem = problem.replace(/-/gi, "+-"); // 5x+2=10+-2x
// Split problem into left and right sides
// Example problem: 5x + 2 = 10 - 2x
var problemArray = problem.split("=");
var problemLeftSide = problemArray[0]; // 5x+2
var problemRightSide = problemArray[1]; // 10+-2x
leftSideXTotal = getTotalX(problemLeftSide);
leftSideIntTotal = getTotalScalars(problemLeftSide);
rightSideXTotal = getTotalX(problemRightSide);
rightSideIntTotal = getTotalScalars(problemRightSide);
// Compute
var totalXs = (leftSideXTotal - rightSideXTotal)
var totalIntegers = (rightSideIntTotal - leftSideIntTotal)
var solution = (totalIntegers / totalXs)
// Display solution
document.getElementById("divSolution").innerText = solution;
// Find the total number of X in the string
function getTotalX(data) {
data = data.replace(/\s/g,'');
xCount = 0;
if(data.indexOf('x') != -1) {
if (data.indexOf('+') != -1) {
data = data.split('+');
for(var i = 0; i < data.length; i++) {
xCount += getTotalX(data[i]);
}
} else if (data.indexOf('-') != -1) {
data = data.split('-');
// Single negative
if(data[0] == "") {
xCount -= getTotalX(data[1]);
} else {
xCount += getTotalX(data[0]);
for(var i = 1; i < data.length; i++) {
xCount -= getTotalX(data[i]);
}
}
} else {
xCount = parseInt(data.split('x')[0]);
}
}
return xCount;
}
// Find the total of scalars
function getTotalScalars(data) {
data = data.replace(/\s/g,'');
intCount = 0;
if (data.indexOf('+') != -1) {
data = data.split('+');
for(var i = 0; i < data.length; i++) {
intCount += getTotalScalars(data[i]);
}
} else if (data.indexOf('-') != -1) {
data = data.split('-');
// Single negative
if(data[0] == "") {
intCount -= getTotalScalars(data[1]);
} else {
intCount += getTotalScalars(data[0]);
for(var i = 1; i < data.length; i++) {
intCount -= getTotalScalars(data[i]);
}
}
} else {
if(data.indexOf('x') == -1) {
intCount = parseInt(data.split('x')[0]);
} else {
intCount = 0;
}
}
return intCount;
}
}
</script>
I'm trying to generate all possible combinations for pair of 1's within given bit width.
Let's say the bit width is 6, i.e. 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 that I'll loop over width - 1 times, and where I shift both a << 1 and b << 1, I'll get all combinations for one pair. After that, I'm pretty much stuck.
Could someone , please, provide some help.
Update: working example
Based on Barmar's mathematical approach, this is what 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/
The numbers with exactly one pair of 1's are the sequence 3, 6, 12, 24, 48, ...; they start with 3 and just double each time.
The numbers with two pairs of 1's are 12+3, 24+3, 24+6, 48+3, 48+6, 48+12, ...; these are the above sequence starting at 12 + the original sequence up to n/4.
The numbers with three pairs of 1's are 48+12+3, 96+12+3, 96+24+3, 96+24+6, ...
The relationship between each of these suggests a recursive algorithm making use of the original doubling sequence. I don't have time right now to write it, but I think this should get you going.
if the bit width isn't that big then you'll be way better off creating bit representations for all numbers from 0 to 31 in a loop and simply ignore the ones that have an odd number of "ones" in the bit representation.
Maybe start counting normally in binary and replace all 1's with 11's like this:
n = 5
n = n.toString(2) //= "101"
n = n.replace(/1/g, "11") //= "11011"
n = parseInt(n, 2) //= 27
So you'll get:
0 -> 0
1 -> 11
10 -> 110
11 -> 1111
100 -> 1100
101 -> 11011
110 -> 11110
111 -> 111111
And so on. You'll have to count up to 31 or so on the left side, and reject ones longer than 6 bits on the right side.
See http://jsfiddle.net/SBH6R/
var len=6,
arr=[''];
for(var i=0;i<len;i++){
for(var j=0;j<arr.length;j++){
var k=j;
if(getNum1(arr[j])%2===1){
arr[j]+=1;
}else{
if(i<len-1){
arr.splice(j+1,0,arr[j]+1);
j++;
}
arr[k]+=0;
}
}
}
function getNum1(str){
var n=0;
for(var i=str.length-1;i>=0;i--){
if(str.substr(i,1)==='1'){n++;}
else{break;}
}
return n;
}
document.write(arr.join('<br />'));
Or maybe you will prefer http://jsfiddle.net/SBH6R/1/. It's simpler, but then you will have to sort() the array:
var len=6,
arr=[''];
for(var i=0;i<len;i++){
for(var k=0,l=arr.length;k<l;k++){
if(getNum1(arr[k])%2===1){
arr[k]+=1;
}else{
if(i<len-1){
arr.push(arr[k]+1);
}
arr[k]+=0;
}
}
}
function getNum1(str){
var n=0;
for(var i=str.length-1;i>=0;i--){
if(str.substr(i,1)==='1'){n++;}
else{break;}
}
return n;
}
document.write(arr.sort().join('<br />'));
See http://jsperf.com/generate-all-combinations-for-pair-of-bits-set-to-1 if you want to compare the performance. It seems that the fastest code is the first one on Chrome but the second one on Firefox.
You can also do this with bit twiddling. If the lowest two bits are zero, we need to set them, which is equivalent to adding 3. Otherwise, we need to replace the lowest block of ones by its top bit and a 1-bit to the left of it. This can be done as follows, where x is the current combination:
x3 = x + 3;
return (((x ^ x3) - 2) >> 2) + x3;