public class RandomIndex { private final int n; private final int m; private int i; private final TinyCipher tc; public RandomIndex(int n, byte[] k) { this.n = n; int b = BitTools.lb(n - 1); this.m = 1 << b; this.i = 0; this.tc = new TinyCipher(b, k); } public int next() { int j; while((j = nextFromM()) >= n); return j; } private int nextFromM() { if (i >= m) throw new IndexOutOfBoundsException(); int j = tc.encrypt(i); ++i; return j; } }