#C4.txt: Help4:=proc(): print(` Snk(n,k), NuSnk(n,k) , LD(L), Rnk(n,k) `): end: #Snk(n,k): Inputs NON-NEG. integer n and an integer k and OUTPUTS #THE SET OF k-element subsets of {1,...,n} #FOR EXAMPLE #Snk(3,2) should be {{1,2},{1,3},{2,3}} Snk:=proc(n,k) local S1,S2,s: option remember: if k<0 or k>n then RETURN({}): fi: if n=0 then if k=0 then RETURN({{}}): else RETURN({}): fi: fi: S1:=Snk(n-1,k): S2:=Snk(n-1,k-1): S1 union {seq( s union {n}, s in S2)}: end: #NuSnk(n,k): Inputs NON-NEG. integer n and an integer k and OUTPUTS #THE NUMBER OF k-element subsets of {1,...,n} #FOR EXAMPLE #NuSnk(3,2) should be 3 NuSnk:=proc(n,k) option remember: if k<0 or k>n then RETURN(0): fi: if n=0 then if k=0 then RETURN(1): else RETURN(0): fi: fi: NuSnk(n-1,k)+ NuSnk(n-1,k-1): end: #LD(L): Inputs a list of positive integers L (of n:=nops(L) members) #outputs an integer i from 1 to n with the prob. of i being #proportional to L[i] #For example LD([1,2,3]) should output 1 with prob. 1/6 #output 2 with prob. 1/3 #output 3 with prob. 3/6=1/2 LD:=proc(L) local n,i,su,r: n:=nops(L): r:=rand(1..convert(L,`+`))(): su:=0: for i from 1 to n do su:=su+L[i]: if r<=su then RETURN(i): fi: od: end: #Rnk(n,k): Inputs NON-NEG. integer n and an integer k and OUTPUTS #A (UNIFORMLY AT-RANDOM) k-element subsets of {1,...,n} #FOR EXAMPLE #Rnk(3,2) should output each of {1,2},{1,3},{2,3} with prob. 1/3 Rnk:=proc(n,k) local c,S: if k<0 or k>n then RETURN(FAIL): fi: if n=0 then if k=0 then RETURN({}): fi: fi: c:=LD([NuSnk(n-1,k), NuSnk(n-1,k-1)]): if c=1 then RETURN(Rnk(n-1,k)): else RETURN(Rnk(n-1,k-1) union {n}): fi: end: