Set using matrix in c#

Asked

Viewed 185 times

4

I have the following matrix:

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


I put such a matrix 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 an array, taking into account the number of columns to determine the size of the set.
In the example cited above, it would be possible to create (3 4) 81 different sets.

Ex.:
[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 scan this array and create column-based sets?

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 on the web something already ready, but I don’t know exactly name what I’m doing.

I would like a solution clean, fast and with little memory consumption.

The matrix given in the question is just an example, because in my code I can build larger matrices. And of course I don’t fill it out line by line as I exemplified.

I believe it is only a question of logic, but good practice makes a lot of difference at this time. By being starting out, I wouldn’t want to make more mistakes than acceptable.

1 answer

2


I imagine that solves any size of matrix

    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--)
            {
                posY[i]++;
                if(posY[i] == linhas)
                {
                    posY[i] = 0;
                }
                else
                {
                    break;
                }
            }
            todos[atual++] = nova;
        }

        return todos;
    }
  • Man, if I could give you + 2, I would! Thank you very much, it worked perfectly. And using primitive types got the way I wanted it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.