google-sheetscombinatorics

Recombining 4 pairs of numbers


I have a question for a personal project of mine, that has stumped me.

The goal is to generate all legal combinations of a set of 8 numbers, that split into 4 pairs. For a combination to be considered legal, each pair has to sum up to 6, 5, 4 or 3, exclusively and with each number being a positive integral. Meaning - assuming the first pair of numbers sums to 6, it will be either 1:5, 2:4, 3:3, 4:2 or 5:1; the second (with sum of 5) will be 1:4, 2:3, 3:2 or 4:1 etc. This means that there are 5 * 4 * 3 * 2 (or 5!) combinations in such an arrangement. I was able to generate those 120 combinations (correctly I hope), however this is just one of the possibilities. The pairs can have any arrangements of the sums, so there are 24 (or 4!) ways the pairs of columns can be arranged, giving a total of 2880 combinations of the set of 8 numbers - that's what I want.

I wasn't able to find a working and not manually intensive solution. Can any of you help? You can use the worksheet I've created for it: https://docs.google.com/spreadsheets/d/1jST8RJunGoMgA14CjHpjNG1rUwa0I6uGWIJzyS9FMY8/edit?usp=sharing


Solution

    1. To generate pairs totalling a list of values (in your example, 6,5,4,3).

    For the example of 6, generate numbers

    1..5

    Generate numbers

    5..1

    Combine them to get

    1|5
    2|4
    

    etc.

    Then repeat this recursively for each total (5,4 and 3 in your example), combining them with the previous result at each stage.

    The formula is

    =ArrayFormula(let(pairs,lambda(self,i,size,if(i>columns(size),"",tocol(sequence(index(size,i)-1)&"|"&index(size,i)-sequence(index(size,i)-1)&"|"&transpose(self(self,i+1,size))))),split(pairs(pairs,1,{3,4,5,6}),"|")))
    
    1. To generate permutations of four numbers

    There are several methods, but the simplest which is fine for small n is to generate all possible combinations of the four numbers including ones with repeated digits and filter them.

    The resulting formula is:

    =let(perms,makearray(256,4,lambda(r,c,mod(quotient(r,4^(4-c)),4)+3)),filter(perms,byrow(perms,lambda(r,countunique(r)))=4))
    
    1. Combining the two formulas:

    Vstack the results for each permutation as follows:

    =ArrayFormula(let(perms,makearray(256,4,lambda(r,c,mod(quotient(r,4^(4-c)),4)+3)),fperms,filter(perms,byrow(perms,lambda(r,countunique(r)))=4),
    pairs,lambda(self,i,size,if(i>columns(size),"",tocol(sequence(index(size,i)-1)&"|"&index(size,i)-sequence(index(size,i)-1)&"|"&transpose(self(self,i+1,size))))),
    reduce({"","","","","","","",""},sequence(rows(fperms)),lambda(a,c,vstack(a,split(pairs(pairs,1,index(fperms,c,0)),"|"))))))