Re: Get all combinations of n digits among m digits

new topic     » goto parent     » topic index » view thread      » older message » newer message

Thank you Pete,

On the following test, the time difference between both methods is high:

atom t0 = time() 
constant test = {1,2,3,4,5,6,7,8,9}  
for i = 1 to 10000 do 
  s = combinations(test,2) 
  s = combinations(test,3) 
  s = combinations(test,4) 
end for  
printf(1, "duration: %f\n", time() - t0) 
t0 = time() 
for i = 1 to 10000 do 
  s = get_combinations(test,2) 
  s = get_combinations(test,3) 
  s = get_combinations(test,4) 
end for  
printf(1, "duration: %f\n", time() - t0) 
 
maybe_any_key() 

duration: 1.741000 
duration: 7.538000 
Press Any Key to continue... 

Here is the OpenEuphoria version:

sequence res = {} 
 
-- Phix function 
public function combinations(sequence s, integer k, integer at=1, sequence res={}, sequence part="")  
  if k=0 then -- got a full set  
    res = append(res,part)  
  elsif at+k-1<=length(s) then  
    -- get all combinations with and without the next item:  
    res = combinations(s,k-1,at+1,res,append(part,s[at]))  
    res = combinations(s,k,at+1,res,part)  
  end if  
  return res  
end function   

Jean-Marc

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu