C# Permutation of an array of arraylists?

后端 未结 13 905
难免孤独
难免孤独 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:57

    Here's a non-recursive, non-Linq solution. I can't help feeling like I could have less looping and calculate the positions with division and modulo, but can't quite wrap my head around that.

    static void Main(string[] args)
        {
            //build test list
            List myList = new List();
            myList.Add(new string[0]);
            myList.Add(new string[0]);
            myList.Add(new string[0]);
            myList[0] = new string[] { "1", "2", "3"};
            myList[1] = new string[] { "4", "5" };
            myList[2] = new string[] { "7", "8", "9" };
    
            object[][] xProds = GetProducts(myList.ToArray());
            foreach(object[] os in xProds)
            {
                foreach(object o in os)
                {
                    Console.Write(o.ToString() + " ");
                }
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    
        static object[][] GetProducts(object[][] jaggedArray){
            int numLists = jaggedArray.Length;
            int nProducts = 1;
            foreach (object[] oArray in jaggedArray)
            {
                nProducts *= oArray.Length;
            }
            object[][] productAry = new object[nProducts][];//holds the results
            int[] listIdxArray = new int[numLists];
            listIdxArray.Initialize();
            int listPtr = 0;//point to current list
    
            for(int rowcounter = 0; rowcounter < nProducts; rowcounter++)
            {
                //create a result row
                object[] prodRow = new object[numLists];
                //get values for each column
                for(int i=0;i= (jaggedArray[listPtr].Length - 1))
                    {
                        listPtr++;
                    }
                    if (listPtr < listIdxArray.Length && listIdxArray[listPtr] < (jaggedArray[listPtr].Length - 1))
                    {
                        //zero out the previous stuff
                        for (int k = 0; k < listPtr; k++)
                        {
                            listIdxArray[k] = 0;
                        }
                        listIdxArray[listPtr]++;
                        listPtr = 0;
                    }
                }
            }
            return productAry;
        }
    

提交回复
热议问题