org.metacsp.utility.Combination Maven / Gradle / Ivy
package org.metacsp.utility;
// 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.*;
//////////////////////////////////////
// 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
public 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;
}
public static void main(String[] args) {
Combination c = new Combination(4,2);
while (c.hasNext()) {
int[] a = c.next();
System.out.println(Arrays.toString(a));
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy