# Untitled

By: a guest on Apr 15th, 2012  |  syntax: None  |  size: 0.94 KB  |  hits: 17  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. How choose random number within range, but weighted toward one part of that range? (in Java)
2. Pick a random number between 1-10
3. If it is <= 6
4.     Return a random number between 1-5
5. Else
6.     Return a random number between 6-10
7. EndIf
8.
9. java.utils.Random randomGenerator = new java.utils.Random();
10. int random = randomGenerator.nextInt(11);
11. if(random <= 6) { //This is 20% more
12.     random = randomGenerator.nextInt(5) + 1;
13. } else {
14.     random = randomGenerator.nextInt(5) + 6;
15. }
16.
17. public int weightedRandom() {
18.   int rand = Math.floor(Math.random() * 5 + 1) // From 1 to 5
19.   if (Math.random() >= 0.6) {
20.     ++rand;
21.   }
22.   return rand;
23. }
24.
25. float sum;
26. do {
27.    sum = rollThreeDice(); // returns 3 to 18, with an average is 10.5
28.    sum -= 10.5;           // Now the range is 0 to 7.5, with the lower end being more likely.
29.    } while(sum < 0);
30. return sum;
31.
32. int x = (int) (number - (Math.random() - Math.random())
33.                     * Math.random() * number);