Created
February 26, 2020 12:14
-
-
Save sonOfRa/6c6871d1dd02cedba0251fa335367cf1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.SecureRandom; | |
class Birthday { | |
public static final int NUM_BITS = 8; | |
public static final int MAX_ID = (1 << NUM_BITS); | |
private static final SecureRandom random = new SecureRandom(); | |
public static void main(String[] args) { | |
// 0.001 = 0.1%, 1 = 100% | |
double targetProbability = 0.001d; | |
long idCount = 1500; | |
double invProbability = 1 / (1 - targetProbability); | |
long twoD = MAX_ID * 2; | |
double result = Math.sqrt(twoD * Math.log(invProbability)); | |
System.out.println("Largest ID: " + MAX_ID); | |
System.out.println("Largest ID in Hex: " + Long.toHexString(MAX_ID)); | |
System.out.printf( | |
"Collision probability of %f%% after %f IDs\n", targetProbability * 100, result); | |
double exponent = (double) (idCount * (idCount - 1)) / 2; | |
double base = (double) (MAX_ID - 1) / MAX_ID; | |
double collisionProbability = (1d - Math.pow(base, exponent)) * 100; | |
System.out.printf( | |
"Collision probability after %d IDs: %f%%\n", idCount, collisionProbability); | |
} | |
public static int generateId() { | |
return random.nextInt(MAX_ID); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment