// maximum for n is 31 or 32 // (32 works but makes things a bit funky because you'll see negative // integers as value, step count and cycle length. Unless you call the // ...AsLong methods.) // TODO: find tap tables for n=25 through 32 // (so for now max is 24) sclass SimpleLSFR { // params int n; // max 32 int start = 1; // calculated int tap, cycleLength; // = 2^n-1 // changing variables int step, value; // tap bit mask for different n's (2 through 24) static final int[] tapTable = { 0x3, 0x3, 0x3, 0x5, 0x3, 0x3, 0x2d, 0x11, 0x9, 0x5, 0x107, 0x27, 0x1007, 0x3, 0x100b, 0x9, 0x81, 0x27, 0x9, 0x5, 0x3, 0x21, 0x87 }; *(int *n) { assertBetween(2, 24, n); cycleLength = (1 << n)-1; tap = tapTable[n-2]; value = start; } int next() { if (++step == cycleLength) step = 0; int tapped = (countBits(value & tap) & 1) ^ 1; ret value = (value >>> 1) | (tapped << (n-1)); } // for debugging/visualization int tapped() { ret value & tap; } int tappedBitCount() { ret countBits(tapped()); } long nextLong() { ret uintToLong(next()); } }