Faster alternative to nested loops?

后端 未结 12 1470
栀梦
栀梦 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:21

    Here's a different way that only need 2 loop. The idea is to increase the first element and if that number goes over than increase the next one.

    Instead of displaying the data, you can use currentValues.Clone and add that cloned version into your list. For me this ran faster than your version.

    byte[] maxValues = {2, 3, 4};
    byte[] currentValues = {0, 0, 0};
    
    do {
        Console.WriteLine("{0}, {1}, {2}", currentValues[0], currentValues[1], currentValues[2]);
    
        currentValues[0] += 1;
    
        for (int i = 0; i <= maxValues.Count - 2; i++) {
            if (currentValues[i] < maxValues[i]) {
                break;
            }
    
            currentValues[i] = 0;
            currentValues[i + 1] += 1;
        }
    
    // Stop the whole thing if the last number is over
    // } while (currentValues[currentValues.Length-1] < maxValues[maxValues.Length-1]);
    } while (currentValues.Last() < maxValues.Last());
    
    • Hope this code works, I converted it from vb

提交回复
热议问题