Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java combination algorithm

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.

like image 231
Marcus Leon Avatar asked Jul 27 '10 17:07

Marcus Leon


People also ask

How do you solve a Java combination problem?

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.

How do you create a combination in Java?

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);

How do you calculate algorithm combinations?

Traditional formula of r-combination (or n choose r) is: C(n, r) = n! / (r! . (n-r)!)

How do you calculate number of combinations in Java?

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.


2 Answers

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);
like image 137
Gopi Avatar answered Oct 12 '22 23:10

Gopi


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());
    }
}
like image 37
Justin Garrick Avatar answered Oct 12 '22 22:10

Justin Garrick