-3

I have an array (java) like this:

String arrName[] = {"John","Paul","Luke","Ana"};

and i want to have an output like this:

JohnPaul
JohnLuke
JohnAna
PaulJohn
PualLuke
PaulAna
LukeJohn
LukePaul
LukeAna
AnaJohn
AnaPaul
AnaLuke

can someone help me???

john17
  • 35
  • 6
  • You need some combination algorythm to do this [Combination](http://en.wikipedia.org/wiki/Combination) here is the libary to solve your problem [combinatoricslib](https://code.google.com/p/combinatoricslib/) – Milkmaid Dec 08 '14 at 05:16
  • you want to know solution or just that someone can help or not :-) – Panther Dec 08 '14 at 05:24
  • possible duplicate of [All possible combinations of an array](http://stackoverflow.com/questions/5162254/all-possible-combinations-of-an-array) –  Dec 08 '14 at 05:35
  • i just want to add 2 elements – john17 Dec 08 '14 at 05:39

2 Answers2

1

Do a cross product between the array and a copy of the array in the form of a nested foreach loop. skip the names that are equal to eachother

String[] copyArrName = arrName;
for (String name : arrName){
    for (String otherName: copyArrName){
        if(name != otherName)
            System.out.println(name + " " + otherName); 
    }
}

this will give you the desired output

Freestyle076
  • 1,548
  • 19
  • 36
  • it will give less combintion in case he has duplicate entry in array. var array Name = {"John" "Paul", "John"}. this code will skip johnjohn. – Panther Dec 08 '14 at 05:33
  • Good point, rather we should use the reference string comparison rather than the string equality comparison. edits incoming! – Freestyle076 Dec 08 '14 at 05:34
-1

You are looking for something like this :-

for(int i=0 ; i < arrName.length ; i++){
    for(int j=0; j< arrName.length; j++){
        if(j != i){
            System.out.println(arrName[i]+arrName[j]);
        }
    }
}
Panther
  • 3,312
  • 9
  • 27
  • 50