Created
May 16, 2019 01:24
-
-
Save gen0cide/653b63f0ff4b5335853a475180c76fef to your computer and use it in GitHub Desktop.
Interview Question: Explain this.
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.util.Random; | |
import java.util.Arrays; | |
public class TheBestRandomWeighted { | |
private static final Random rand = new Random(); | |
public static void main(String[] argv) { | |
int low = 0; | |
int dip = 12; | |
int peak = 88; | |
int max = 100; | |
int result = randomWeighted(low, dip, peak, max); | |
System.out.println("Result: " + result); | |
} | |
public static int random(int low, int high) { | |
return low + rand.nextInt(high - low + 1); | |
} | |
public static int randomWeighted(int low, int dip, int peak, int max) { | |
int total = 0; | |
int probability = 100; | |
int[] probArray = new int[max + 1]; | |
for (int x = 0; x < probArray.length; x++) { | |
total += probArray[x] = probability; | |
if (x < dip || x > peak) { | |
probability -= 3; | |
} else { | |
probability += 3; | |
} | |
} | |
int hit = random(0, total); | |
total = 0; | |
for (int x = 0; x < probArray.length; x++) { | |
if (hit >= total && hit < (total + probArray[x])) { | |
return x; | |
} | |
total += probArray[x]; | |
} | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mmcloughlin prove your worth