Combination
A permutation is a group of generated numbers in an order, but a combination is a group of numbers without an order.
As with permutations, we use a combination generation class with a skip function.
Combinatorial generation is basically a class like this:
public class Combination{
private int N;
private int R;
public int[] Index=null;
private bool First=false;
public Combination( int N, int R ){
this.N=N;
this.R=R;
if( R>0 && R<=N ){
Cmb=new int[R];
Cmb[0]=0;
for( int m=1; m<R; m++ ) Index[m]=Index[m-1]+1;
First=true;
}
}
public bool Successor(int skip=int.MaxValue){
if(N<=0) return false;
if(First){ First=false; return (Index!=null); }
int k;
if(Index[0]==N-R) return false;
if(skip<R-1){
for(k=skip; k>=0; k--){ if(Index[k]<=N-R) break; }
if(k<0) return false;
}
else{
for(k=R-1; k>0 && Index[k]==N-R+k; --k);
}
++Index[k];
for(int j=k; j<R-1; ++j) Index[j+1]=Index[j]+1;
return true;
}
}
Combination is used as follows.
The change position of the next combination generation can be changed dynamically.
The position specification is from 0 to (combination size - 1),
In other cases, or if the specification is omitted, the skip function will not work.
>var cmb = new Combination (6,3);
int skip=4;
while(cmb.Successor(skip) ){
// (Evaluation process : Set change position skip for next combination generation)
}Test code
static void Main( string[ ] args ){
for( int skip=0; skip<5; skip++ ){
Combination cmb = new Combination(6,4);
Console.WriteLine("\n ===== Combination(6,4) skip={0}",skip );
while( cmb.Successor(skip) ) Console.WriteLine(cmb);
Console.ReadKey();
}
}
Execution results
static void Main( string[ ] args ){
for( int skip=0; skip<5; skip++ ){
Combination cmb = new Combination(6,4);
Console.WriteLine("\n ===== Combination(6,4) skip={0}",skip );
while( cmb.Successor(skip) ) Console.WriteLine(cmb);
Console.ReadKey();
}
}(left: combination generation results, right: working data inside the function)
===== Combination(6,4) skip=0
0 1 2 3
1 2 3 4
2 3 4 5
===== Combination(6,4) skip=1
0 1 2 3
0 2 3 4
0 3 4 5
1 2 3 4
1 3 4 5
2 3 4 5
===== Combination(6,4) skip=2
0 1 2 3
0 1 3 4
0 2 3 4
0 3 4 5
1 2 3 4
1 3 4 5
2 3 4 5
===== Combination(6,4) skip=3
0 1 2 3
0 1 2 4
0 1 2 5
0 1 3 4
0 1 3 5
0 1 4 5
0 2 3 4
0 2 3 5
0 2 4 5
0 3 4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5
===== Combination(6,4) skip=4
0 1 2 3
0 1 2 4
0 1 2 5
0 1 3 4
0 1 3 5
0 1 4 5
0 2 3 4
0 2 3 5
0 2 4 5
0 3 4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5