Combination function




On Sat, 8 May 2010, Iago Tejeda P?rez wrote:

< Hi guys,
< 
< I was looking for a function that returns the combinations of n elements in groups of r. I only found a function that returns the number of posible
< combinations(n,r).
< 
< I'm trying to implement myself, but I didn't get anything useful yet. I'll try until I find another solution.
< 
< If anybody knows anything about it, let me know it.
< 
< Thanks in advance.
< Iago.
< 
< 


Are you looking for something like this?

(%i1) choices[S,n] := block([c:{},s],
  if length(S)>n then
  for r in S do (
    s:delete(r,S),
    c:union(c,choices[s,n]))
  else c:{S},
  c)$
(%i2) s : setify(makelist(i,i,1,6));
(%o2)                         {1, 2, 3, 4, 5, 6}
(%i3) choices[s,2];
(%o3) {{1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {2, 3}, {2, 4}, {2, 5}, {2, 6},
                                {3, 4}, {3, 5}, {3, 6}, {4, 5}, {4, 6},{5, 6}}

The point is that you construct your subset of n elements by deleting
N-n elements from your set S of size N. This can be done recursively,
in which case I've chosen to use an array function to memorize results,
because the possibilities grow quite quickly with N.

Leo
-- 
The University of Edinburgh is a charitable body, registered in
Scotland, with registration number SC005336.