Reputation: 1641
I have an array of ints (e.g. 0, 2, 4, 7). Each value from the array I'd like to combine with another value of the array so that there should be every combination possible(e.g. [0, 2], [0, 4], [0, 7] but also [2, 0], [4, 0] and [7,0] and same for rest of values). What is the best and most resources (processing) effective way to achieve that?
thank you
Upvotes: 0
Views: 109
Reputation: 28697
int[] arr = [...];
for(int i : arr){
for(int j : arr){
// Do something with both "i and j".
}
}
Within the processing point (the "do something" comment), you could do something as simple as printing the result, or adding the combination result to a new array or collection. (The later would be less ideal for performance reasons, as it would require all possible combinations to be stored in-memory at once - instead of processing the results as you generate them.)
Upvotes: 1
Reputation: 18578
iterate j
from i+1
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
System.out.println("["+arr[i] +","+arr[j]+"]");
System.out.println("["+arr[j] +","+arr[i]+"]");
}
}
EXAMPLE:
Upvotes: 2