Given a collection of integers, what's a Java algorithm that will give all pairs of items as follows..
Given the example collection: [1,3,5], we'd want the output:
[1-1]
[3-3]
[5-5]
[1-3]
[1-5]
[3-5]
Note that ordering is not important, so we want one of [1-3], [3-1] but not both.
This should work with a collection of n numbers, not just the the three numbers as in this example.
In the combination formula, we need to calculate the factorial of n, r and n-r. In the main method, we create a list of numbers and add certain elements to it. We use the size() method to get the number of elements in the list. We set a constant value 2 to r, i.e., the number of items being chosen at a time.
Next, let's use the combinations method to generate combinations: Set<Set<Integer>> combinations = Sets. combinations(ImmutableSet. of(0, 1, 2, 3, 4, 5), 3);
Traditional formula of r-combination (or n choose r) is: C(n, r) = n! / (r! . (n-r)!)
getFact(n)/(getFact(n-r)*getFact(r)): This is the formula n!/((n-r)!. r!). getFact() method has been explained in finding the factorial of a number in Java post. This is the way in which we can calculate the number of combinations nCr is calculated provided the value of n and r.
Below function should do this
private void printPermutations(int[] numbers) {
for(int i=0;i<numbers.length; i++) {
for (int j=i; j<numbers.length; j++) {
System.out.println("[" + numbers[i] + "-"+ numbers[j] +"]");
}
}
}
Example call to this function
int[] numbers={1,2,3};
printPermutations(numbers);
Sounds like homework...but here it is anyway. Obviously you can do without an ArrayList, etc. - just quick and dirty.
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
int[] input = {1, 3, 5};
ArrayList<String> output = new ArrayList<String>();
int n = input.length;
for (int left = 0; left < n; left++) {
output.add("["+input[left]+"-"+input[left]+"]");
for (int right = left + 1; right < n; right++) {
output.add("["+input[left]+"-"+input[right]+"]");
}
}
System.out.println(output.toString());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With