aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/rschwietzke/FastRandom.java
blob: 2d25d35402866f0cc43260f417c656c289d8de66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 *  Copyright 2023 The original authors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.rschwietzke;

/**
 * Ultra-fast pseudo random generator that is not synchronized!
 * Don't use anything from Random by inheritance, this will inherit
 * a volatile! Not my idea, copyied in parts some demo random
 * generator lessons.
 *
 * @author rschwietzke
 *
 */
public class FastRandom {
    private long seed;

    public FastRandom() {
        this.seed = System.currentTimeMillis();
    }

    public FastRandom(long seed) {
        this.seed = seed;
    }

    protected int next(int nbits) {
        // N.B. Not thread-safe!
        long x = this.seed;
        x ^= (x << 21);
        x ^= (x >>> 35);
        x ^= (x << 4);
        this.seed = x;

        x &= ((1L << nbits) - 1);

        return (int) x;
    }

    /**
     * Borrowed from the JDK
     *
     * @param bound
     * @return
     */
    public int nextInt(int bound) {
        int r = next(31);
        int m = bound - 1;
        if ((bound & m) == 0) // i.e., bound is a power of 2
            r = (int) ((bound * (long) r) >> 31);
        else {
            for (int u = r; u - (r = u % bound) + m < 0; u = next(31))
                ;
        }
        return r;
    }

    /**
     * Borrowed from the JDK
     * @return
     */
    public int nextInt() {
        return next(32);
    }
}