Skip to content

Instantly share code, notes, and snippets.

@gen0cide
Created May 16, 2019 01:24
Show Gist options
  • Save gen0cide/653b63f0ff4b5335853a475180c76fef to your computer and use it in GitHub Desktop.
Save gen0cide/653b63f0ff4b5335853a475180c76fef to your computer and use it in GitHub Desktop.
Interview Question: Explain this.
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;
}
}
@gen0cide
Copy link
Author

@mmcloughlin prove your worth

@gen0cide
Copy link
Author

@davehughes and I are waiting superstar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment