package Sequenic.T2.Engines; import java.math.BigInteger; /** * This implements a generator producing all sequences of length * r whose elements are to be chosen from a set of n elements. * In other words, it produces all possible cartesian product over * n elements. * * @author Wishnu Prasetya */ public class SequenceGenerator extends CombinationGenerator { public SequenceGenerator(int n, int r) { assert n>0 && r>=0 ; this.n = n ; this.r = r ; a = new int[r]; try { long total = power(n,r) ; if (total <= (long) Integer.MAX_VALUE) this.total = (int) total ; else throw new Error("The number of combinations is too large.") ; } catch (ArithmeticException e) { throw new Error("The number of combinations is too large.",e) ; } reset(); } /** * Calculate n^r. */ static protected long power(int n, int r) { long x = 1 ; long n_ = n ; while (r>0) { x = n_ * x ; r-- ; } return x ; } //------ // Reset //------ @Override public void reset() { numLeft = total ; } /** * Generate next sequence. */ @Override public void getNext(int[] res) { assert res.length == a.length ; assert numLeft > 0 ; numLeft-- ; int x = numLeft ; int i = 0 ; while (i>> a.size = " + a.length) ; while (x > 0) { a[i] = x % n ; x = x / n ; i++ ; } copyArray(a,res) ; return ; } }