Permutation between arrays in Java

Asked

Viewed 339 times

2

I am trying to create a code that generates a data matrix. This matrix consists of all possibilities between certain arrays.

My arrays are:

[Corretor, Clientes]
[Para Voce, Para sua Familia, Para Todos]
[Masculino, Feminino]
[Sim, Nao]
[Solteiro, Casado, Divorciado, Viuvo]
[Ate 4k, de 4k a 8k, de 8k a 12k, de 12k a 16k, acima de 16k]
[Essencial, Sob medida, Superior]

From this, I want to create a code that manages all the possibilities between these arrays. That is, it can return me an array, for example, in this way:

[Broker, For You, Male, Yes, Single, Up to 4k, Essential]

The codes I made and studied just give me the possibilities within an array and not between two or more arrays.

public class Permutar {
    public static void permutar(int[] conjunto, int p) {
        if (p == 3) {
            System.out.printf("{%d, %d, %d}%n", conjunto[0], conjunto[1], conjunto[2]);
        } else {
            do {
                permutar(conjunto, p + 1);
                conjunto[p]++;
            } while (conjunto[p] < 3);
            conjunto[p] = 0;
        }
    }
    public static void main(String[] args) {
        int[] conjunto = {0, 0, 0};
        permutar(conjunto, 0);
    }
}

1 answer

2


Supposing your arrays are these:

String[] v1 = { "Corretor", "Clientes" };
String[] v2 = { "Para Voce", "Para sua Familia", "Para Todos" };
String[] v3 = { "Masculino", "Feminino" };
String[] v4 = { "Sim", "Nao" };
String[] v5 = { "Solteiro", "Casado", "Divorciado", "Viuvo" };
String[] v6 = { "Ate 4k", "de 4k a 8k", "de 8k a 12k", "de 12k a 16k", "acima de 16k" };
String[] v7 = { "Essencial", "Sob medida", "Superior" };

One way to generate all combinations is by using recursion:

public void permutacoes(String[][] arrays, List<String[]> result, int indiceAtual, String combinacao) {
    if (indiceAtual == arrays.length) {
        // split para gerar um array
        result.add(combinacao.split(","));
        return;
    }

    for (int i = 0; i < arrays[indiceAtual].length; i++) {
        permutacoes(arrays, result, indiceAtual + 1,
                    combinacao+ (combinacao.isEmpty() ? "" : ", ") + arrays[indiceAtual][i]);
    }
}

Basically, the indiceAtual indicates which of the arrays I am currently in. For each of them, I run it and I run a permutation going to the next array, and I concatenate the text, using the commas to separate each part.

At the end, I’ll have the list result, containing all combinations, and then just scroll through this list to print your elements.

To use this method, simply create a new array containing the original arrays, and call it zero as the initial index and the String empty as the first combination:

// array contendo todos os outros arrays
String[][] m = { v1, v2, v3, v4, v5, v6, v7 };
List<String[]> result = new ArrayList<>();
permutacoes(m, result, 0, "");
result.forEach(r -> System.out.printf("%s\n", Arrays.asList(r)));

I use Arrays.asList to turn the array into a list, so the output looks like this:

[Corretor,  Para sua Familia,  Feminino,  Nao,  Viuvo,  acima de 16k,  Sob medida]
[Corretor,  Para sua Familia,  Feminino,  Nao,  Viuvo,  acima de 16k,  Superior]
[Corretor,  Para Todos,  Masculino,  Sim,  Solteiro,  Ate 4k,  Essencial]
[Corretor,  Para Todos,  Masculino,  Sim,  Solteiro,  Ate 4k,  Sob medida]

But of course, once you have the array, you can scroll through it and print your elements the way you want.


Recursion-free

If you don’t want to use recursion, the simplest way (and in this case a little "ugly") is to use several nested loops, one for each array:

List<String[]> result = new ArrayList<>();
for (String s1 : v1) {
    for (String s2 : v2) {
        for (String s3 : v3) {
            for (String s4 : v4) {
                for (String s5 : v5) {
                    for (String s6 : v6) {
                        for (String s7 : v7) {
                            result.add(new String[] { s1, s2, s3, s4, s5, s6, s7 });
                        }
                    }
                }
            }
        }
    }
}

In this case, I admit that it was not a very beautiful code, as it became a variation of the "hadouken of if's":

But the end result is the same.

  • a doubt here, could not solve with flatMap? I was curious hahaha

  • 1

    @Cezarcruz If you are talking about the flatMap of the stream API, I see no reason to use it here. But if you want, can try and add an answer, it would be interesting to see other solutions :-)

  • Actually I do not know if it is possible, I’m really curious hahaha, if you find, I put the link. thanks.

Browser other questions tagged

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