Created
September 12, 2011 11:16
-
-
Save jenaiz/1211037 to your computer and use it in GitHub Desktop.
Expand a random range from 1-5 to 1-7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
public class Randoms { | |
final static Random rand = new Random(); | |
final static int TOTAL = 1000; | |
public static void main(String[] args) { | |
printProbabilityRand5(); | |
printProbabilityRand7(); | |
} | |
public static int rand5() { | |
return rand.nextInt(5) + 1; | |
} | |
private static int rand7() { | |
int j = 0; | |
for (int i = 1; i < 8; i++) { | |
j += rand5() * i; | |
} | |
return j % 7 + 1; | |
} | |
private static void printProbabilityRand5() { | |
int zero = 0; | |
int one = 0; | |
int two = 0; | |
int three = 0; | |
int four = 0; | |
int five = 0; | |
for (int i = 0; i < TOTAL; i++) { | |
int random = rand5(); | |
switch (random) { | |
case 0: | |
zero++; | |
break; | |
case 1: | |
one++; | |
break; | |
case 2: | |
two++; | |
break; | |
case 3: | |
three++; | |
break; | |
case 4: | |
four++; | |
break; | |
case 5: | |
five++; | |
break; | |
} | |
} | |
System.out.println("zero : " + (double) zero / TOTAL + " - one : " | |
+ (double) one / TOTAL + " - two : " + (double) two / TOTAL | |
+ " - three : " + (double) three / TOTAL + " - four : " | |
+ (double) four / TOTAL + " - five : " + (double) five / TOTAL); | |
} | |
private static void printProbabilityRand7() { | |
int zero = 0; | |
int one = 0; | |
int two = 0; | |
int three = 0; | |
int four = 0; | |
int five = 0; | |
int six = 0; | |
int seven = 0; | |
for (int i = 0; i < TOTAL; i++) { | |
int random = rand7(); | |
switch (random) { | |
case 0: | |
zero++; | |
break; | |
case 1: | |
one++; | |
break; | |
case 2: | |
two++; | |
break; | |
case 3: | |
three++; | |
break; | |
case 4: | |
four++; | |
break; | |
case 5: | |
five++; | |
break; | |
case 6: | |
six++; | |
break; | |
case 7: | |
seven++; | |
break; | |
} | |
} | |
System.out.println("zero : " + (double) zero / TOTAL + " - one : " | |
+ (double) one / TOTAL + " - two : " + (double) two / TOTAL | |
+ " - three : " + (double) three / TOTAL + " - four : " | |
+ (double) four / TOTAL + " - five : " + (double) five / TOTAL | |
+ " + six : " + (double) six / TOTAL + " + seven : " | |
+ (double) seven / TOTAL); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment