How can I find all of the permutations consisting of 1 element from a variable number of arrays of variable length?

后端 未结 4 1369
名媛妹妹
名媛妹妹 2020-12-12 02:36

I have an array U of arrays D that vary in length. I need to be able to return all permutations of array indices that would select a different perm

4条回答
  •  粉色の甜心
    2020-12-12 03:18

    So ... what about this isn't straightforward?

    You want an iterator. You want it to iterate over the last array. When it gets to the end of that array, increment its current position in the second-last array and go back to the start of the last array.

    psuedocode using C#s yield return syntax:

    foreach n1 in a1
        foreach n2 in a2
            foreach n3 in a3
                yield return (n1, n2, n3)
    

    EDIT: If the number of sets varies, you could use some form of recursion:

    function next(list)
        firstArray = list.first
        iterator = iterator(list.rest)
        if !iterator
            foreach i in firstArray
                yield return i
        else
            foreach i in firstArray
                while (iterator.hasNext)
                    yield return (i, iterator.next)
    

    Consider the behaviour when a list of length 1 is passed in, then consider the behaviour for a list of length 2, and satisfy yourself that it does in fact work.

提交回复
热议问题