C# Permutation of an array of arraylists?

后端 未结 13 904
难免孤独
难免孤独 2020-11-27 18:10

I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.

EXAMPLE: (all values are strings)

         


        
13条回答
  •  一向
    一向 (楼主)
    2020-11-27 18:43

    I recently ran across a similar problem in a project of mine and stumbled on this question. I needed a non-recursive solution that could work with lists of arbitrary objects. Here's what I came up with. Basically I'm forming a list of enumerators for each of the sub-lists and incrementing them iteratively.

    public static IEnumerable> GetPermutations(IEnumerable> lists)
    {
        // Check against an empty list.
        if (!lists.Any())
        {
            yield break;
        }
    
        // Create a list of iterators into each of the sub-lists.
        List> iterators = new List>();
        foreach (var list in lists)
        {
            var it = list.GetEnumerator();
            // Ensure empty sub-lists are excluded.
            if (!it.MoveNext())
            {
                continue;
            }
            iterators.Add(it);
        }
    
        bool done = false;
        while (!done)
        {
            // Return the current state of all the iterator, this permutation.
            yield return from it in iterators select it.Current;
    
            // Move to the next permutation.
            bool recurse = false;
            var mainIt = iterators.GetEnumerator();
            mainIt.MoveNext(); // Move to the first, succeeds; the main list is not empty.
            do
            {
                recurse = false;
                var subIt = mainIt.Current;
                if (!subIt.MoveNext())
                {
                    subIt.Reset(); // Note the sub-list must be a reset-able IEnumerable!
                    subIt.MoveNext(); // Move to the first, succeeds; each sub-list is not empty.
    
                    if (!mainIt.MoveNext())
                    {
                        done = true;
                    }
                    else
                    {
                        recurse = true;
                    }
                }
            }
            while (recurse);
        }
    }
    

提交回复
热议问题