Set using array in C #

Posted on

Question :

I have the following array:

a   d   k   m
s   j   e   r
t   c   f   p

I put such array in an array as follows:

char[,] matriz = new char[3,4];
matriz[0,0] = 'a';
matriz[0,1] = 'd';
matriz[0,2] = 'k';
matriz[0,3] = 'm';
matriz[1,0] = 's';
// E assim sucessivamente.

I would like to generate all possible sets based on such array, taking into account quantity of columns to determine the size of the set.
In the above example, it would be possible to create (3 ^ 4) 81 different sets.

[1] "adkm"     [4] "adem"    [8] "adfm"      [11] "ajkm"
[2] "adkr"     [5] "ader"    [9] "adfr"      [12] "ajkr"
[3] "adkp"     [7] "adep"    [10] "adfp"     [13] "ajkp"

What would be the best way to wipe this array and create sets based on the columns?

int qtdColunas = 4;

char[] conjunto1 = new char[qtdColunas];
conjunto1[0] = 'a';
conjunto1[1] = 'd';
conjunto1[2] = 'k';
conjunto1[3] = 'm';

char[] conjunto2 = new char[qtdColunas];
conjunto1[0] = 'a';
conjunto1[1] = 'd';
conjunto1[2] = 'k';
conjunto1[3] = 'r';

char[] conjunto3 = new char[qtdColunas];
conjunto1[0] = 'a';
conjunto1[1] = 'd';
conjunto1[2] = 'k';
conjunto1[3] = 'p';

I tried to find something on the web already, but I can not exactly name what I’m doing.
I would like a clean, fast and low memory consumption solution.
The matrix given in the question is just an example, because in my code I can construct larger arrays. And of course I do not fill it line by line as exemplified.
I think it’s just a matter of logic, but good practice makes a lot of difference at the moment. By beginning, I would not want to make any more mistakes than acceptable.


Answer :

I imagine this will resolve any array size

    public static string[] TodosPossiveis(char[,] letras)
        int linhas = letras.GetUpperBound(0) + 1;
        int colunas = letras.GetUpperBound(1) + 1;
        int max = (int)Math.Pow(linhas, colunas);
        string[] todos = new string[max];

        int[] posY = new int[colunas];

        int atual = 0;
        while(atual < max)
            string nova = "";
            for(int i = 0; i < colunas; i++)
                nova += letras[posY[i], i];
            for(int i = colunas-1; i > -1; i--)
                if(posY[i] == linhas)
                    posY[i] = 0;
            todos[atual++] = nova;

        return todos;


Leave a Reply

Your email address will not be published. Required fields are marked *