4 ms·
I love doing stuff like this for fun. Sometimes I try to get nice algorithms into tweets. Here is one of my favorites so far, returns the powerset for array '
by binarymax 15y ago
I love doing stuff like this for fun. Sometimes I try to get nice algorithms into tweets. Here is one of my favorites so far, returns the powerset for array 'a':
function P(a){for(p=[],i=Math.pow(2,l=a.length);i;)for(b=i.toString(2),j=k=b.length,p[--i]=[];j;)if(b[--j]==1)p[i].push(a[j+l-k]);return p}
I know that there are some big gotchas here, such as b and p being declared globally due to lack of var...but I gave up trying to gain an extra 4 bytes for function(a,b,p). Also the subset arrays are in reverse order.
- jedschmidt 15y agoThere's a lot of room in there: Math.pow(2,l=a.length) 1<<(l=a.length) are the same, as are these: if(b[--j]==1) ~-b[--j]||
- binarymax 15y agoThanks! This is an amazing guide. I forsee many more lost hours shaving and shaving with this in hand.
- jedschmidt 15y agoJust remember to fork the master gist (https://gist.github.com/962807 https://gist.github.com/962807) when you're done, and add an annotation so that the rest of us can learn from it!
- binarymax 15y agoThanks! This is an amazing guide. I forsee many more lost hours shaving and shaving with this in hand.