Re: Get all combinations of n digits among m digits

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

Here's the Phix equivalent - yep, it's a builtin, and yep, results are in lexicographic order.

constant test = {1,2,4,6,7,9}  
?{"pairs",combinations(test,2)} 
?{"triplets",combinations(test,3)} 
-- {"pairs",{{1,2},{1,4},{1,6},{1,7},{1,9},{2,4},{2,6},{2,7},{2,9},{4,6},{4,7},{4,9},{6,7},{6,9},{7,9}}} 
-- {"triplets",{{1,2,4},{1,2,6},{1,2,7},{1,2,9},{1,4,6},{1,4,7},{1,4,9},{1,6,7},{1,6,9},{1,7,9},{2,4,6},{2,4,7},{2,4,9},{2,6,7},{2,6,9},{2,7,9},{4,6,7},{4,6,9},{4,7,9},{6,7,9}}} 

And here's how I implemented that, in builtins/permute.e, slightly simplified (removing unique, deep_copy and any dependency on Phix's automatic pbr):

global function combinations(sequence s, integer k, integer at=1, sequence part="")  
    if k=0 then -- got a full set  
        return {part} 
    elsif at+k-1<=length(s) then  
        -- get all combinations with and without the next item:  
        return combinations(s,k-1,at+1,append(part,s[at]))  
              &combinations(s,k,at+1,part)  
    end if  
    return {} 
end function   
new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu