2

I have a string array = String[] str = {"a","b","c","d"} that I want o multiply with itself thrice to get triplets in this form = {a,b,c}..and so on.

I wrote this code:

String[] str = {"a","b","c","d"};

    for(int i=0; i<str.length;i++){
        for(int j=1;j<str.length;j++){
            for(int k=2; k<str.length;k++){

                System.out.println(str[i]+"_"+str[j]+"_"+str[k]);

            }
        }
    }

But the output I get looks like this:

a_b_c
a_b_d
a_c_c
a_c_d
a_d_c
a_d_d
b_b_c
b_b_d

I want only unique combinations: a_b_c, a_b_d, a_c_d, b_c_d

Can I get some help here please?

Niras
  • 445
  • 4
  • 8
  • 19
  • Please read [Why is β€œCan someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) before attempting to ask more questions. –  Jun 06 '18 at 23:40

1 Answers1

1

You can skip repeated strings by using continue if you're processing elements that are equal.

String[] str = {"a","b","c","d"};

for (int i = 0; i < str.length; i++) {
    for (int j = 1; j < str.length; j++) {
        if (str[j].equals(str[i]))
            continue;
        for (int k = 2; k < str.length; k++) {
            if (str[k].equals(str[i]) || str[k].equals(str[j]))
                continue;
            System.out.println(str[i] + "_" + str[j] + "_" + str[k]);
        }
    }
}

If you know that str does not contain duplicate elements (or if you want to include duplicates in that case), then you can skip based on equality of indices rather than elements:

for (int i = 0; i < str.length; i++) {
    for (int j = 1; j < str.length; j++) {
        if (i == j)
            continue;
        for (int k = 2; k < str.length; k++) {
            if (i == k || j == k)
                continue;
            System.out.println(str[i] + "_" + str[j] + "_" + str[k]);
        }
    }
}
k_ssb
  • 6,024
  • 23
  • 47