(Java) Find all possible pairs in an array

When I try to do something like this, I understand that I really need to go to university!

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

I found out about recursion, but I cannot find an answer for this.

thanks

+4
source share
3 answers

In case the 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 contains unique strings!

+9
source

I provide an example that prints all possible Strings n-tuples, just set the reqLen attribute 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(""); }} 
+2
source

This is 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 comments noted, if the elements [a, b, c] have only one ab and therefore not ba , (called a 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 
+1
source

Source: https://habr.com/ru/post/1303337/


All Articles