Post Reply 
Little problem(s) July 2022
07-04-2022, 11:11 PM
Post: #3
RE: Little problem(s) July 2022
I am not sure if this match the requirements.
Here is Lua's solution, which should be trivial to convert to Python
Note: Lua index is 1-based; Python 0-based.

Code:
function f(lst, x)
    local idx = {}
    for i=1,#lst do idx[i] = i end
    return recurse(lst, x, idx, 0, 0)
end    
    
function recurse(lst, x, idx, n, prev)
    if x==0 then print(unpack(idx,1,n)); return end    
    n = n+1 -- setup for next item
    for i = n, #lst do
        local y = idx[i]
        if prev > y then continue end   -- idx combinations
        y = x - lst[y]
        if y < 0 then continue end
        idx[n], idx[i] = idx[i], idx[n] -- swap
        recurse(lst, y, idx, n, idx[n])   
        idx[n], idx[i] = idx[i], idx[n] -- restore
    end
end

For index permutations instead of combinations, remove if prev > y then ... line

lua> L1, L2 = {1,2,3,2,2,1}, 6
lua> f(L1, L2) -- L1 index combinations that sum to L2
1      2      3
1      2      4      6
1      2      5      6
1      3      4
1      3      5
1      4      5      6
2      3      6
2      4      5
3      4      6
3      5      6
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
Little problem(s) July 2022 - pier4r - 07-04-2022, 06:04 PM
RE: Little problem(s) July 2022 - Albert Chan - 07-04-2022 11:11 PM
RE: Little problem(s) July 2022 - pauln - 07-05-2022, 01:01 AM
RE: Little problem(s) July 2022 - pier4r - 07-05-2022, 10:00 AM
RE: Little problem(s) July 2022 - pier4r - 07-05-2022, 01:56 PM
RE: Little problem(s) July 2022 - pier4r - 07-07-2022, 10:51 AM
RE: Little problem(s) July 2022 - DavidM - 07-07-2022, 12:02 PM
RE: Little problem(s) July 2022 - DavidM - 07-07-2022, 03:09 PM
RE: Little problem(s) July 2022 - pier4r - 07-07-2022, 05:19 PM
RE: Little problem(s) July 2022 - Werner - 07-06-2022, 07:48 AM
RE: Little problem(s) July 2022 - DavidM - 07-07-2022, 05:27 PM
RE: Little problem(s) July 2022 - pier4r - 07-07-2022, 05:37 PM
RE: Little problem(s) July 2022 - pauln - 07-11-2022, 05:34 AM
RE: Little problem(s) July 2022 - pauln - 07-11-2022, 10:32 PM



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