File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * Given a function which generates a random integer in the range 1 to 7,
3+ * write a function which generates a random integer in the range 1 to 10 uniformly.
4+ * <p/>
5+ * 1 2 3 4 5 6 7
6+ * 1 1 2 3 4 5 6 7
7+ * 2 8 9 10 1 2 3 4
8+ * 3 5 6 7 8 9 10 1
9+ * 4 2 3 4 5 6 7 8
10+ * 5 9 10 1 2 3 4 5
11+ * 6 6 7 8 9 10 * *
12+ * 7 * * * * * * *
13+ * <p/>
14+ * <p/>
15+ * http://en.wikipedia.org/wiki/Rejection_sampling
16+ * <p/>
17+ * The main idea is when you generate a number in the desired range,
18+ * output that number immediately. If the number is out of the desired range,
19+ * reject it and re-sample again. As each number in the desired range has
20+ * the same probability of being chosen, a uniform distribution is produced.
21+ */
22+ public class Rand {
23+ public static int rand7 () {
24+ // the higher of factor of random, the higher of precision of random 7
25+ return (int ) (Math .random () * 100 ) % 7 ;
26+ }
27+
28+ public static int rand10 () {
29+ while (true ) {
30+ int row = rand7 () * 7 ;
31+ int col = rand7 ();
32+ int index = col + row ;
33+ if (index < 40 ) {
34+ return index % 10 ;
35+ }
36+ }
37+ }
38+
39+ public static void main (String [] args ) {
40+ /* Test: call rand10 many times and inspect the results. */
41+ int [] arr = new int [10 ];
42+ int test_size = 1000000 ;
43+ for (int k = 0 ; k < test_size ; k ++) {
44+ arr [rand10 ()]++;
45+ }
46+
47+ for (int i = 0 ; i < 10 ; i ++) {
48+ double percent = 100.0 * arr [i ] / test_size ;
49+ System .out .println (i + " appeared " + percent + "% of the time." );
50+ }
51+ }
52+ }
You can’t perform that action at this time.
0 commit comments