// Combinations.java // Computes nCr -- all the ways you can combine r choices among n total objects. // Unlike permutations, here order does not matter, so {0,1,2} is the same as {0,2,1}. import java.util.*; public class Combinations { public static void main(String[] args) { test1(); test2(); } public static void test1() { Combination c = new Combination(4,2); while (c.hasNext()) { int[] a = c.next(); System.out.println(Arrays.toString(a)); } } public static void test2() { Scanner scanner = new Scanner(System.in); System.out.print("Enter n: "); int n = scanner.nextInt(); System.out.print("Enter r: "); int r = scanner.nextInt(); Combination c = new Combination(n,r); System.out.println("Here are all the ways you can combine " + r + " choices among " + n + " objects:"); int counter = 0; while (c.hasNext()) { int[] next = c.next(); System.out.println(Arrays.toString(next)); counter++; } System.out.println("total = " + n + "C" + r + " = " + counter); } } ////////////////////////////////////// // Combination // // You do not need to write the code below here. // You just need to be able to USE it. ////////////////////////////////////// // The algorithm is from Applied Combinatorics, by Alan Tucker. // Based on code from koders.com class Combination { private int n, r; private int[] index; private boolean hasNext = true; public Combination(int n, int r) { this.n = n; this.r = r; index = new int[r]; for (int i = 0; i= 0) { index[i] = index[i]+1; for (int j = i+1; j=0; i--) if (index[i] < n - r + i) return i; return -1; } }