Faster alternative to nested loops?

后端 未结 12 1449
栀梦
栀梦 2020-12-12 18:35

I have a need to create a list of combinations of numbers. The numbers are quite small so I can use byte rather than int. However it requires many

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 19:10

    Here is another solution. Outside of VS it runs as fast as 437.5 ms which is 26% faster than the original code (593.7 on my computer):

    static List Combinations(byte[] maxs)
    {
      int length = maxs.Length;
      int count = 1; // 3981312;
      Array.ForEach(maxs, m => count *= m);
      byte[][] data = new byte[count][];
      byte[] counters = new byte[length];
    
      for (int r = 0; r < count; r++)
      {
        byte[] row = new byte[length];
        for (int c = 0; c < length; c++)
          row[c] = counters[c];
        data[r] = row;
    
        for (int i = length - 1; i >= 0; i--)
        {
          counters[i]++;
          if (counters[i] == maxs[i])
            counters[i] = 0;
          else
            break;
        }
      }
    
      return data.ToList();
    }
    

提交回复
热议问题