View Javadoc
1   /*
2    * License : The MIT License
3    * Copyright(c) 2022 olyutorskii
4    */
5   
6   package io.github.olyutorskii.aletojio.rng.dull;
7   
8   import io.github.olyutorskii.aletojio.rng.RndInt32;
9   import io.github.olyutorskii.aletojio.rng.RndInt64;
10  import java.util.List;
11  import java.util.Objects;
12  
13  /**
14   * Just repeating integer sequence generator.
15   *
16   * <p>If X0,X1,X2 is specified, outputs {X0, X1, X2, X0, X1, X2, X0...} forever.
17   *
18   * <p>Yes, all pseudo-random generators on finite state automaton are repeated.
19   */
20  public class SeqRepeater implements RndInt32, RndInt64 {
21  
22      private final int[] iVec;
23      private final int size;
24  
25      private int pos;
26  
27  
28      /**
29       * Constructor.
30       *
31       * @param iVecArg int values sequence
32       * @throws NullPointerException null argument
33       * @throws IllegalArgumentException no values
34       */
35      public SeqRepeater(int... iVecArg)
36              throws NullPointerException, IllegalArgumentException {
37          super();
38          Objects.requireNonNull(iVecArg);
39  
40          this.size = iVecArg.length;
41          if (this.size < 1) throw new IllegalArgumentException();
42  
43          this.iVec = new int[this.size];
44          System.arraycopy(iVecArg, 0, this.iVec, 0, this.size);
45  
46          this.pos = 0;
47  
48          return;
49      }
50  
51      /**
52       * Constructor.
53       *
54       * @param iVecList int values sequence
55       * @throws NullPointerException argument is null
56       * @throws IllegalArgumentException no values
57       */
58      public SeqRepeater(List<Integer> iVecList)
59              throws NullPointerException, IllegalArgumentException {
60          super();
61          Objects.requireNonNull(iVecList);
62  
63          this.size = iVecList.size();
64          if (this.size < 1) throw new IllegalArgumentException();
65  
66          this.iVec = new int[this.size];
67  
68          int idx = 0;
69          for (int iVal : iVecList) {
70              this.iVec[idx++] = iVal;
71          }
72          assert idx == this.size;
73  
74          this.pos = 0;
75  
76          return;
77      }
78  
79  
80      /**
81       * {@inheritDoc}
82       *
83       * @return {@inheritDoc}
84       */
85      @Override
86      public int nextInt32() {
87          int result = this.iVec[this.pos++];
88  
89          if (this.pos >= this.size) {
90              this.pos = 0;
91          }
92  
93          return result;
94      }
95  
96      /**
97       * {@inheritDoc}
98       *
99       * @return {@inheritDoc}
100      */
101     @Override
102     public long nextInt64() {
103         long rndHigh = Integer.toUnsignedLong(nextInt32());
104         long rndLow  = Integer.toUnsignedLong(nextInt32());
105         long result = (rndHigh << Integer.SIZE) | rndLow;
106         return result;
107     }
108 
109 }