Hello.
For those interested, here is a generator of r-combinations. There is nothing wrong with Daehls, I just wanted something simpler to understand as the problem intrigued me, so this is probably slower. I found the pseudo code in a buggy! :mad: pdf document somwhere. (Daehls delist handler is something that seems to be a great way to translate items into indicies IMO.)
set comboList to {}
combination(comboList, 3, 6)
listprint(comboList)
(*
"{1, 2, 3}
{1, 2, 4}
{1, 2, 5}
{1, 2, 6}
{1, 3, 4}
{1, 3, 5}
{1, 3, 6}
{1, 4, 5}
{1, 4, 6}
{1, 5, 6}
{2, 3, 4}
{2, 3, 5}
{2, 3, 6}
{2, 4, 5}
{2, 4, 6}
{2, 5, 6}
{3, 4, 5}
{3, 4, 6}
{3, 5, 6}
{4, 5, 6}"
*)
on combination(combinations, r, n)
# print the first r combination
set S to {}
repeat with i from 1 to r
set end of S to i
end repeat
copy S to end of combinations
repeat with i from 2 to C(n, r)
set m to r
set max_val to n
repeat while (((item m) of S) = max_val)
set m to m - 1
set max_val to max_val - 1
end repeat
# increment the above rightmost element
set item m of S to (item m of S) + 1
# all others are the successors:
repeat with j from (m + 1) to r
set item j of S to (item (j - 1) of S) + 1
end repeat
copy S to end of combinations
end repeat
end combination
on listprint(theL)
try
text 0 of theL
on error e
set ofs to offset of "{" in e
set tmp to text (ofs + 1) thru -3 of e
tell (a reference to text item delimiters)
set astid to contents of it
set contents of it to "}, "
set newl to text items of tmp
set contents of it to "}" & return
set newt to newl as text
set contents of it to astid
end tell
return newt
end try
end listprint
on C(n, r)
# Counts the number of r-combinations in a set of n elements.
# it is also called the binomial coeffecient.
if n = 0 or n < r or r < 0 then error "C: argument error"
return (factorial(n) div (factorial(r) * (factorial(n - r))))
end C
on factorial(n)
if n > 170 then error "Factorial: n too large."
# Result greater than 1.797693E+308!
if n < 0 then error "Factorial: n not positive."
set a to 1
repeat with i from 1 to n
set a to a * i
end repeat
return a
end factorial
Edit
Made a “fancier” listprint handler.