Post Reply 
COMBOSET - Subsets of a set S of size n
03-07-2017, 02:25 AM (This post was last modified: 03-08-2017 11:54 PM by Han.)
Post: #1
COMBOSET - Subsets of a set S of size n
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

Graph 3D | QPI | SolveSys
Find all posts by this user
Quote this message in a reply
Post Reply 




User(s) browsing this thread: 1 Guest(s)