Skip to content

Instantly share code, notes, and snippets.

View futuresecurity's full-sized avatar

futuresecurity

View GitHub Profile
@futuresecurity
futuresecurity / GridCoordHashSeed.java
Created August 22, 2019 20:46
How to deterministically initalize a PRNG from (x, y) coordinates.
/* How to deterministically initalize a PRNG from (x, y) coordinates. The
* exact algorithm choice is arbitrary. `coordToLong` could be even simpler.
* The "hash" is a good scrambling function from 64-bit input to 64-bit
* output. Hashing might be redundant for certain PRNG implementations, but
* only if the implementation already mixes seeds very well. (Similar seeds
* can produce outputs with the same patterns.) If you use another RNG then
* you need to bundle its source with your project. C's "srand" should not
* be used because the same seed can produce different results on different
* platforms.
*/
@futuresecurity
futuresecurity / biased int sampling fragment .java
Created September 25, 2018 22:00
Fast approximately uniform int sampling algorithm. See "Fast Random Integer Generation in an Interval" by Daniel Lemire for a similar unbiased algorithm.
default int nextInt_Biased(int upperBound)
{
if (upperBound == 0) { return nextInt(); }
if (upperBound == 1) { return 0; }
final long unsignedLimit = upperBound & 0xFFFF_FFFFL;
final int log2Ceil = 64 - Long.numberOfLeadingZeros(unsignedLimit - 1);
final int bitsOfRandomness = 64 - log2Ceil;
final long rand = nextUnsignedLongBits(bitsOfRandomness);
return (int)(long)((rand * unsignedLimit) >>> bitsOfRandomness);
@futuresecurity
futuresecurity / BoundedIntSampling.java
Last active September 24, 2018 18:07
Experimental uniform int sampling algorithm. Requires a UniformGenerator capable of producing up to 32 bit samples. Outputs a number in [0, bound - 1]. It builds on java.util.Random's nextInt(int) algorithm. It factors `bound` to better handle more values of `bound`. (Special care is taken for the factors which are a power of two. It avoids usin…
package io.github.futuresecurity.random.sampling;
import io.github.futuresecurity.random.UniformGenerator;
import java.util.SplittableRandom;
public class BoundedIntSampling
{
public static int randomInt_TwoFactor32(int bound, UniformGenerator rng)
{