views:

290

answers:

3

Its when I try to do stuff like this I realise I really need to go to university!

Anyway I have an array of strings (275) I need to loop through them and create strings of all the possible pairs, in java.

I've been learning about recursion but I cant find the answer for this.

Thanks

A: 

It's a simple double-loop:

for(int x = 0; x < 275; x++) {
    final String first = arrayOfStrings[x];
    for(int y = 0; y < 275; y++) {
        if(y == x) continue; // will properly increase y
        final String second = arrayOfStrings[y];
        // TODO: do stuff with first and second.
    }
}

Edit: as the comments noted, if the elements [a, b, c] have only one ab and thus not ba, (called combination), then the following code will work:

final ArrayList<String> collected = new ArrayList<String>();
for(int x = 0; x < 275; x++) {
    for(int y = 0; y < 275; y++) {
        if(y == x) continue; // will properly increase y
        final String p1 = arrayOfStrings[x] + arrayOfStrings[y];
        final String p2 = arrayOfStrings[y] + arrayOfStrings[x];
        if(!collected.contains(p1) && !collected.contains(p2)) {
            collected.add(p1);
        }
    }
}
// TODO: do stuff with collected
Pindatjuh
+1  A: 

In case pairs ab and ba are different, do:

for i=0 to array.length
  for j=0 to array.length
    if i == j skip
    else construct pair array[i], array[j] 

and if not, do something like this:

for i=0 to array.length-1
  for j=i+1 to array.length
    construct pair array[i], array[j] 

Note that I am assuming the array holds unique strings!

Bart Kiers
A: 

I am providing an example that prints all possible n-tuples Strings, just set the attribute reqLen to 2 and it prints all possible pairs.

public class MyString {

String[] chars = {"a", "b", "c"};
int reqLen = 2;

private void formStrings(String crtStr){

    if (crtStr.length() == reqLen){

        System.out.println(crtStr);
        return;
    }
    else
        for (int i = 0; i < chars.length; i++) 
            formStrings(crtStr + chars[i]);

}

public static void main(String[] args) {

    new MyString().formStrings("");
}}
abdelatif