HP Forums
COMBOSET - Subsets of a set S of size n - Printable Version

+- HP Forums (https://www.hpmuseum.org/forum)
+-- Forum: HP Software Libraries (/forum-10.html)
+--- Forum: HP Prime Software Library (/forum-15.html)
+--- Thread: COMBOSET - Subsets of a set S of size n (/thread-7892.html)



COMBOSET - Subsets of a set S of size n - Han - 03-07-2017 02:25 AM

Usage: COMBOSET(set, size) where set is a set of objects, and size refers to the desired size of the subsets.

Example: COMBOSET({1, "b", (2,-1), [1,2], 3.14}, 3)

{
{1,"b",2-i},
{1,"b",[1,2]},
{1,"b",3.14},
{1,2-i,[1,2]},
{1,2-i,3.14},
{1,[1,2],3.14},
{"b",2-i,[1,2]},
{"b",2-i,3.14},
{"b",[1,2],3.14},
{2-i,[1,2],3.14}
}

Code:
EXPORT COMBOSET(s,n)
BEGIN
  local l:={};
  local sl:={};
  local tl:={};
  local i,j;
  local m:=size(s);
  n:=IP(n); // ensure n is an integer to avoid infinite loop

  case
    if n==m then l:={s}; end;
    if n==1 then l:=makelist({s(X)},X,1,m); end; 
    if n>m then l:={}; end;
    for i from 2 to m-n+2 do
      sl:=sub(s,i,m); 
      tl:=COMBOSET(sl,n-1);
      for j from 1 to size(tl) do
        tl(j):=concat({s(i-1)},tl(j));
      end;
      l:=concat(l,tl); 
    end;
  end;
END;

See also:

http://www.hpmuseum.org/forum/thread-2845.html
http://www.hpmuseum.org/forum/thread-7759.html