Created
January 15, 2012 12:50
-
-
Save shiawuen/1615760 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html lang="en-US"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Combination – stupid way</title> | |
</head> | |
<body> | |
<script src="index.js"></script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Given a number n, generate all possible sequences of numbers that add up to n, where the numbers in the | |
sequence are in non-ascending order. | |
e.g., n=4, then | |
4 | |
3,1 | |
2,2 | |
2,1,1 | |
1,1,1,1 | |
*/ | |
(function(slice, MAX, undef) { | |
/** | |
* Change this value to get different sets | |
* of number combinations | |
*/ | |
var n = 15; | |
/** | |
* Value to get benchmark and calculate total | |
* sets generated | |
*/ | |
var count = 0; | |
var start, now; | |
start = +new Date() | |
compute(n); | |
now = +new Date() | |
// end | |
console.log('Total time spent: ' +(now-start)+ 'ms'); | |
console.log(count + ' combinations generated'); | |
function compute(n1 /*, n2, n3 */) { | |
var set = slice.call(arguments) | |
, idx = set.length-1 | |
, last = set[idx] | |
, base = set[idx-1] | |
, i = last | |
, newSet; | |
if (base === undef) | |
base = MAX; | |
if (last <= base) { | |
count += 1; | |
console.log(set+''); | |
} | |
while(--i) { | |
// Get a copy of the existing set | |
newSet = slice.call(set); | |
// Skip those that have new value that | |
// is larger than the base | |
if (i > base) continue; | |
newSet[idx] = i; | |
newSet.push(last-i); | |
compute.apply(null, newSet); | |
} | |
} | |
})(Array.prototype.slice, Infinity); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment