Re: Get combinations of digits in a sequence

new topic     » goto parent     » topic index » view thread      » older message » newer message
jmduro said...

I try to understand how to use permute with my sequence which has sub-items of different lengths. It s too much for my old brain. Could you provide an example using my SEQ constant as an input?

Sorry, I didn't mean permute, I meant the comb function (also on that page), modified for your specific requirements something like this:

constant SEQ = {{4,8,9}, {1,2,4}, {1,4,5,6}}  
  
function comb(sequence pool, integer unique=0, sequence res={}, integer i=1, sequence chosen={}) 
    if i>length(pool) then  -- got a full set 
        res = append(res,chosen) 
    else 
        -- get all combinations with something from pool[i] 
        for j=1 to length(pool[i]) do 
            object pij = pool[i][j] 
            if not unique or not find(pij,chosen) then 
                res = comb(pool,unique,res,i+1,append(chosen,pij)) 
            end if 
        end for 
    end if 
    return res 
end function          
?comb(SEQ) 
?comb(SEQ,1) 

Same results as your code, but with the initialisation to {} now automated, and an accidental reset by a second task/thread mid-way through now completely impossible.

Lengthy searches through some huge number of combinations are precisely the sort of thing that gets shunted off to a background task/thread, and therefore it is important to ensure they cannot tread on each others toes.

Otherwise, this code is very similar to what you posted.

An alternative that allows early termination:

constant SEQ = {{4,8,9}, {1,2,4}, {1,4,5,6}}  
  
function comb(sequence pool, integer rid, integer unique=0, integer i=1, sequence chosen={}) 
    if i>length(pool) then  -- got a full set 
        if not call_func(rid,{chosen}) then return 0 end if 
    else 
        -- get all combinations with something from pool[i] 
        for j=1 to length(pool[i]) do 
            object pij = pool[i][j] 
            if not unique or not find(pij,chosen) then 
                if not comb(pool,rid,unique,i+1,append(chosen,pij)) then return 0 end if 
            end if 
        end for 
    end if 
    return 1    -- carry on 
end function          
 
function test(sequence s) 
    ?s 
    if equal(s,{4,1,6}) then return 0 end if 
    return 1    -- carry on 
end function 
 
?comb(SEQ,routine_id("test"))   -- {4,1,1} {4,1,4} {4,1,5} {4,1,6} 
?comb(SEQ,routine_id("test"),1) -- {4,1,5} {4,1,6} 

Pete

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

Search



Quick Links

User menu

Not signed in.

Misc Menu