Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- P(1) = 2
- P(2) = 3
- P(3) = 5
- int[] numsToGenerate = new int[] { 1, 2, 3, 4, 5 };
- double[] discreteProbabilities = new double[] { 0.1, 0.25, 0.3, 0.25, 0.1 };
- 2, 5, 6, 5, 2
- 1 1
- 2 2 2 2 2
- 3 3 3 3 3 3
- 4 4 4 4 4
- 5 5
- public class DistributedRandomNumberGenerator {
- private Map<Integer, Double> distribution;
- private double distSum;
- public DistributedRandomNumberGenerator() {
- distribution = new HashMap<>();
- }
- public void addNumber(int value, double distribution) {
- if (this.distribution.get(value) != null) {
- distSum -= this.distribution.get(value);
- }
- this.distribution.put(value, distribution);
- distSum += distribution;
- }
- public int getDistributedRandomNumber() {
- double rand = Math.random();
- double ratio = 1.0f / distSum;
- double tempDist = 0;
- for (Integer i : distribution.keySet()) {
- tempDist += distribution.get(i);
- if (rand / ratio <= tempDist) {
- return i;
- }
- }
- return 0;
- }
- }
- DistributedRandomNumberGenerator drng = new DistributedRandomNumberGenerator();
- drng.addNumber(1, 0.3d); // Adds the numerical value 1 with a probability of 0.3 (30%)
- // [...] Add more values
- int random = drng.getDistributedRandomNumber(); // Generate a random number
- public static void main(String[] args) {
- DistributedRandomNumberGenerator drng = new DistributedRandomNumberGenerator();
- drng.addNumber(1, 0.2d);
- drng.addNumber(2, 0.3d);
- drng.addNumber(3, 0.5d);
- int testCount = 1000000;
- HashMap<Integer, Double> test = new HashMap<>();
- for (int i = 0; i < testCount; i++) {
- int random = drng.getDistributedRandomNumber();
- test.put(random, (test.get(random) == null) ? (1d / testCount) : test.get(random) + 1d / testCount);
- }
- System.out.println(test.toString());
- }
- {1=0.20019100000017953, 2=0.2999349999988933, 3=0.4998739999935438}
- final int ran = myRandom.nextInt(100);
- if (ran > 50) { return 3; }
- else if (ran > 20) { return 2; }
- else { return 1; }
- t[0] = 1; t[1] = 1; // ... one for each possible result
- return t[ran];
- Random r=new Random();
- double[] weights=new double[]{0.1,0.1+0.2,0.1+0.2+0.5};
- // end of init
- double random=r.nextDouble();
- // next perform the binary search in weights array
Add Comment
Please, Sign In to add comment