-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRand7FromRand5.java
More file actions
50 lines (43 loc) · 1.09 KB
/
Rand7FromRand5.java
File metadata and controls
50 lines (43 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package math;
/**
* Create a random number generator with equal probability from 1 to 7 using a
* random number generator that gives number from 1 to 5.
*
* Link: http://www.geeksforgeeks.org/generate-integer-from-1-to-7-with-equal-
* probability/
*
* @author shivam.maharshi
*/
public class Rand7FromRand5 {
public static int rand_7() {
int[][] vals = {
{ 1, 2, 3, 4, 5 },
{ 6, 7, 1, 2, 3 },
{ 4, 5, 6, 7, 1 },
{ 2, 3, 4, 5, 6 },
{ 7, 0, 0, 0, 0 }
};
int result = 0;
while (result == 0)
{
int i = rand5();
int j = rand5();
result = vals[i-1][j-1];
}
return result;
}
public static int rand7() {
int n = 5 * rand5() + rand5() - 5;
while (n > 21) {
n += 5 * rand5() + rand5() - 5;
}
return n % 7 + 1;
}
private static int rand5() {
return (int) (5 * Math.random()) + 1;
}
public static void main(String[] args) {
System.out.println(rand7());
System.out.println(rand_7());
}
}