Home > database >  Finding All Combinations of a Multidimention Array with a Max Value in C#
Finding All Combinations of a Multidimention Array with a Max Value in C#

Time:08-01

Let's say I have an int[8,6] array which can have the maximum value of 255 per cell and I want to find all combinations of this array.

What is the most efficient way to accomplish this?

Min array, Max Array

CodePudding user response:

For array size N (1D array for simpliciry, 2D case works similar) and maximum value M there are M^N possible combinations. Every combination corresponds to value in range 0..M^N-1, so we can just walk throug this range and get combination for every value. Of course, it is possible for reasonable small values of N and M.

Python-like pseudocode:

int A[N]
P = M**N  #math.intpower(M, N)
for i in range(P):
    t = i
    for k in range(N):  #number of cells, number of digits in counter value
        A[k] = t % M  # value in k-th cells of result for variant number i
        t = t // M  #integer division 

Note that for base M=256 you perhaps don't need to use division - needed values are just bytes of multibyte representation of big number in base 256

  • Related