Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

48
LINES

< > BotCompany Repo | #1035200 // SimpleLSFR - linear feedback shift register (repeating pseudo-RNG with a cycle length of 2^n-1, using ints, works)

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (7975L/45K).

1  
// maximum for n is 31 or 32
2  
// (32 works but makes things a bit funky because you'll see negative
3  
// integers as value, step count and cycle length. Unless you call the
4  
// ...AsLong methods.)
5  
// TODO: find tap tables for n=25 through 32
6  
//       (so for now max is 24)
7  
8  
sclass SimpleLSFR {
9  
  // params
10  
  int n; // max 32
11  
  int start = 1;
12  
  
13  
  // calculated
14  
  int tap, cycleLength; // = 2^n-1
15  
  
16  
  // changing variables
17  
  int step, value;
18  
  
19  
  // tap bit mask for different n's (2 through 24)
20  
  static final int[] tapTable = {
21  
    0x3, 0x3, 0x3, 0x5,
22  
    0x3, 0x3, 0x2d, 0x11,
23  
    0x9, 0x5, 0x107, 0x27,
24  
    0x1007, 0x3, 0x100b, 0x9,
25  
    0x81, 0x27, 0x9, 0x5,
26  
    0x3, 0x21, 0x87
27  
  };
28  
  
29  
  *(int *n) {
30  
    assertBetween(2, 24, n);
31  
    cycleLength = (1 << n)-1;
32  
    tap = tapTable[n-2];
33  
    value = start;
34  
  }
35  
  
36  
  int next() {
37  
    if (++step == cycleLength) step = 0;
38  
    
39  
    int tapped = (countBits(value & tap) & 1) ^ 1;
40  
    ret value = (value >>> 1) | (tapped << (n-1));
41  
  }
42  
  
43  
  // for debugging/visualization
44  
  int tapped() { ret value & tap; }
45  
  int tappedBitCount() { ret countBits(tapped()); }
46  
47  
  long nextLong() { ret uintToLong(next()); }
48  
}

Author comment

Began life as a copy of #1035196

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, ekrmjmnbrukm, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1035200
Snippet name: SimpleLSFR - linear feedback shift register (repeating pseudo-RNG with a cycle length of 2^n-1, using ints, works)
Eternal ID of this version: #1035200/4
Text MD5: cb7509eb456f2f3f900ef99c4e6c7be8
Transpilation MD5: c106765482b5037611d31e6e7b3b2818
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-04-15 01:32:10
Source code size: 1198 bytes / 48 lines
Pitched / IR pitched: No / No
Views / Downloads: 131 / 182
Version history: 3 change(s)
Referenced in: [show references]