Skip to content

Instantly share code, notes, and snippets.

@ssanin82
Created December 25, 2014 08:13
Show Gist options
  • Save ssanin82/eedc2af06b14a5355e9f to your computer and use it in GitHub Desktop.
Save ssanin82/eedc2af06b14a5355e9f to your computer and use it in GitHub Desktop.
public class Combinations {
int n;
int k;
int[] current;
boolean init;
public Combinations(int n, int k) {
this.n = n;
this.k = k;
this.current = new int[k];
this.init = false;
}
boolean next() {
if (!init) {
for (int i = 0; i < k; ++i) {
current[i] = i;
}
init = true;
} else {
int pos = k - 1;
while (true) {
if (current[pos] < (n - 1)) {
boolean yield = true;
int m = ++current[pos];
while (++pos != k) {
if (m < (n - 1)) {
current[pos] = ++m;
} else {
--pos;
yield = false;
break;
}
}
if (yield) {
break;
}
} else {
if (0 == pos) {
return false;
} else {
--pos;
}
}
}
}
return true;
}
public int[] access() {
return current;
}
void dump() {
for (int i = 0; i < k; ++i) {
System.out.print(current[i]);
}
System.out.println();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment