Find all combinations of two arrays

前端 未结 5 682
长情又很酷
长情又很酷 2021-02-15 17:02

I am trying to find all the combination of two arrays, but with an important variation:

Each value of the second array needs to be spread out over the val

5条回答
  •  清歌不尽
    2021-02-15 17:36

    I think I came up with one possible solution, but I’m certain it’s far from efficiënt.

    Given the arrays:

    left = [A, B, C]
    right = [1, 2, 3]
    

    First create a power set of right:

    []
    [1]
    [2]
    [3]
    [1, 2]
    [1, 3]
    [2, 3]
    [1, 2, 3]
    

    Then have nested loops through this for each value in left. Each loop will check if the value is not already in the previous loop and the last loop will also check if all values are present.

    In psuedo this would look something like this:

    for x in powerset
        a = x
        for y in powerset
            if y not in x
                b = y
                for z in powerset
                    if z not in y and z not in x and [x + y + z] = right
                        c = z
                        displayresult
    

    Edit

    Here's this crappy inefficient solution in javascript. Posting it for completion sake.

    https://jsfiddle.net/6o03d3L3/

    function loop(left, right, powerSet, depth, siblings) {
        for (var i=0; i

提交回复
热议问题