Combinations: Difference between revisions
Content deleted Content added
CoffeeScript |
|||
Line 510: | Line 510: | ||
(printf "%s " n)) |
(printf "%s " n)) |
||
(printf "%n")))</lang> |
(printf "%n")))</lang> |
||
=={{header|CoffeeScript}}== |
|||
Basic backtracking solution. |
|||
<lang coffeescript> |
|||
combinations = (n, p) -> |
|||
return [ [] ] if p == 0 |
|||
i = 0 |
|||
combos = [] |
|||
combo = [] |
|||
while combo.length < p |
|||
if i < n |
|||
combo.push i |
|||
i += 1 |
|||
else |
|||
break if combo.length == 0 |
|||
i = combo.pop() + 1 |
|||
if combo.length == p |
|||
combos.push clone combo |
|||
i = combo.pop() + 1 |
|||
combos |
|||
clone = (arr) -> (n for n in arr) |
|||
N = 5 |
|||
for i in [0..N] |
|||
console.log "------ #{N} #{i}" |
|||
for combo in combinations N, i |
|||
console.log combo |
|||
</lang> |
|||
output |
|||
<lang>> coffee combo.coffee |
|||
------ 5 0 |
|||
[] |
|||
------ 5 1 |
|||
[ 0 ] |
|||
[ 1 ] |
|||
[ 2 ] |
|||
[ 3 ] |
|||
[ 4 ] |
|||
------ 5 2 |
|||
[ 0, 1 ] |
|||
[ 0, 2 ] |
|||
[ 0, 3 ] |
|||
[ 0, 4 ] |
|||
[ 1, 2 ] |
|||
[ 1, 3 ] |
|||
[ 1, 4 ] |
|||
[ 2, 3 ] |
|||
[ 2, 4 ] |
|||
[ 3, 4 ] |
|||
------ 5 3 |
|||
[ 0, 1, 2 ] |
|||
[ 0, 1, 3 ] |
|||
[ 0, 1, 4 ] |
|||
[ 0, 2, 3 ] |
|||
[ 0, 2, 4 ] |
|||
[ 0, 3, 4 ] |
|||
[ 1, 2, 3 ] |
|||
[ 1, 2, 4 ] |
|||
[ 1, 3, 4 ] |
|||
[ 2, 3, 4 ] |
|||
------ 5 4 |
|||
[ 0, 1, 2, 3 ] |
|||
[ 0, 1, 2, 4 ] |
|||
[ 0, 1, 3, 4 ] |
|||
[ 0, 2, 3, 4 ] |
|||
[ 1, 2, 3, 4 ] |
|||
------ 5 5 |
|||
[ 0, 1, 2, 3, 4 ] |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |