View Javadoc
1   /*
2    * License : The MIT License
3    * Copyright(c) 2022 olyutorskii
4    */
5   
6   package io.github.olyutorskii.aletojio.shrink;
7   
8   import io.github.olyutorskii.aletojio.rng.RndInt32;
9   import java.util.ArrayList;
10  import java.util.Arrays;
11  import java.util.Collection;
12  import java.util.Objects;
13  
14  /**
15   * Mixing entropy of N random number streams by XOR.
16   *
17   * <p>Random number output throughput decreases {@code 1/N}.
18   */
19  @SuppressWarnings("serial")
20  public class XorMixer implements RndInt32 {
21  
22      private final Collection<RndInt32> rnds;
23  
24  
25      /**
26       * Constructor.
27       *
28       * @param rndColl random streams
29       * @throws NullPointerException argument or stream is null
30       * @throws IllegalArgumentException no stream
31       */
32      public XorMixer(Collection<RndInt32> rndColl)
33              throws NullPointerException, IllegalArgumentException {
34          super();
35          Objects.requireNonNull(rndColl);
36  
37          if (rndColl.isEmpty()) {
38              throw new IllegalArgumentException();
39          }
40  
41          for (RndInt32 rnd : rndColl) {
42              Objects.requireNonNull(rnd);
43          }
44  
45          this.rnds = new ArrayList<>(rndColl);
46  
47          return;
48      }
49  
50      /**
51       * Constructor.
52       *
53       * @param rndVec random streams
54       * @throws NullPointerException argument is null
55       * @throws IllegalArgumentException no stream
56       */
57      public XorMixer(RndInt32... rndVec)
58              throws NullPointerException, IllegalArgumentException {
59          this(Arrays.asList(rndVec));
60          return;
61      }
62  
63      /**
64       * {@inheritDoc}
65       *
66       * @return {@inheritDoc}
67       */
68      @Override
69      public int nextInt32() {
70          int result = 0x00;
71  
72          for (RndInt32 rnd : this.rnds) {
73              result ^= rnd.nextInt32();
74          }
75  
76          return result;
77      }
78  
79  }