Guest User

Untitled

a guest
Mar 22nd, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. P(1) = 2
  2. P(2) = 3
  3. P(3) = 5
  4.  
  5. int[] numsToGenerate = new int[] { 1, 2, 3, 4, 5 };
  6. double[] discreteProbabilities = new double[] { 0.1, 0.25, 0.3, 0.25, 0.1 };
  7.  
  8. 2, 5, 6, 5, 2
  9.  
  10. 1 1
  11. 2 2 2 2 2
  12. 3 3 3 3 3 3
  13. 4 4 4 4 4
  14. 5 5
  15.  
  16. public class DistributedRandomNumberGenerator {
  17.  
  18. private Map<Integer, Double> distribution;
  19. private double distSum;
  20.  
  21. public DistributedRandomNumberGenerator() {
  22. distribution = new HashMap<>();
  23. }
  24.  
  25. public void addNumber(int value, double distribution) {
  26. if (this.distribution.get(value) != null) {
  27. distSum -= this.distribution.get(value);
  28. }
  29. this.distribution.put(value, distribution);
  30. distSum += distribution;
  31. }
  32.  
  33. public int getDistributedRandomNumber() {
  34. double rand = Math.random();
  35. double ratio = 1.0f / distSum;
  36. double tempDist = 0;
  37. for (Integer i : distribution.keySet()) {
  38. tempDist += distribution.get(i);
  39. if (rand / ratio <= tempDist) {
  40. return i;
  41. }
  42. }
  43. return 0;
  44. }
  45.  
  46. }
  47.  
  48. DistributedRandomNumberGenerator drng = new DistributedRandomNumberGenerator();
  49. drng.addNumber(1, 0.3d); // Adds the numerical value 1 with a probability of 0.3 (30%)
  50. // [...] Add more values
  51.  
  52. int random = drng.getDistributedRandomNumber(); // Generate a random number
  53.  
  54. public static void main(String[] args) {
  55. DistributedRandomNumberGenerator drng = new DistributedRandomNumberGenerator();
  56. drng.addNumber(1, 0.2d);
  57. drng.addNumber(2, 0.3d);
  58. drng.addNumber(3, 0.5d);
  59.  
  60. int testCount = 1000000;
  61.  
  62. HashMap<Integer, Double> test = new HashMap<>();
  63.  
  64. for (int i = 0; i < testCount; i++) {
  65. int random = drng.getDistributedRandomNumber();
  66. test.put(random, (test.get(random) == null) ? (1d / testCount) : test.get(random) + 1d / testCount);
  67. }
  68.  
  69. System.out.println(test.toString());
  70. }
  71.  
  72. {1=0.20019100000017953, 2=0.2999349999988933, 3=0.4998739999935438}
  73.  
  74. final int ran = myRandom.nextInt(100);
  75. if (ran > 50) { return 3; }
  76. else if (ran > 20) { return 2; }
  77. else { return 1; }
  78.  
  79. t[0] = 1; t[1] = 1; // ... one for each possible result
  80. return t[ran];
  81.  
  82. Random r=new Random();
  83. double[] weights=new double[]{0.1,0.1+0.2,0.1+0.2+0.5};
  84. // end of init
  85. double random=r.nextDouble();
  86. // next perform the binary search in weights array
Add Comment
Please, Sign In to add comment