Commit 86f68d7d authored by Dominikus Herzberg's avatar Dominikus Herzberg

Neuer Commit

parent f88c53f8
import java.util.Random;
// tag::KlasseKonstruktor[]
class MC {
int answers, solutions;
int minGuesses, maxGuesses;
int[] crosses;
MC(int answers, int solutions, int minGuesses, int maxGuesses) {
assert answers >= 1 && solutions <= answers;
assert minGuesses >= 0 && minGuesses <= maxGuesses && maxGuesses <= answers;
this.answers = answers;
this.solutions = solutions;
this.minGuesses = minGuesses;
this.maxGuesses = maxGuesses;
crosses = new int[answers];
for(int i = 1; i <= answers; i++) crosses[i-1] = i;
}
// end::KlasseKonstruktor[]
// tag::simulate[]
boolean simulate() {
Random random = new Random();
int guesses = minGuesses + random.nextInt(maxGuesses - minGuesses + 1);
if (guesses != solutions) return false;
MC.shuffle(crosses);
for(int i = 1; i <= guesses; i++) {
if (crosses[i-1] > solutions) return false;
}
return true;
}
// end::simulate[]
// tag::run[]
double run(long samples) {
long count = 0;
for(long i = 1; i <= samples; i++) {
count += simulate() ? 1 : 0;
}
return (double) count / (double) samples;
}
// end::run[]
// tag::shuffle[]
static void shuffle(int[] a) {
Random random = new Random();
for(int i = 0; i < a.length; i++) {
int j = random.nextInt(a.length);
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
// end::shuffle[]
// tag::KlasseKonstruktor[]
}
// end::KlasseKonstruktor[]
// tag::Tests[]
double tolerance = 0.005;
long runs = 1_000_000;
assert Math.abs(new MC(4,1,1,1).run(runs)-1.0/4) <= tolerance : "Test 1";
assert Math.abs(new MC(4,1,1,2).run(runs)-1.0/4/2) <= tolerance : "Test 2";
assert Math.abs(new MC(4,1,1,3).run(runs)-1.0/4/3) <= tolerance : "Test 3";
assert Math.abs(new MC(4,1,1,4).run(runs)-1.0/4/4) <= tolerance : "Test 4";
assert Math.abs(new MC(4,3,3,3).run(runs)-1.0/4) <= tolerance : "Test 5";
assert Math.abs(new MC(4,2,2,2).run(runs)-1.0/6) <= tolerance : "Test 6";
assert Math.abs(new MC(4,2,1,2).run(runs)-1.0/6/2) <= tolerance : "Test 7";
assert Math.abs(new MC(4,2,1,3).run(runs)-1.0/6/3) <= tolerance : "Test 8";
assert Math.abs(new MC(4,2,1,4).run(runs)-1.0/6/4) <= tolerance : "Test 9";
assert Math.abs(new MC(4,2,2,3).run(runs)-1.0/6/2) <= tolerance : "Test 10";
assert Math.abs(new MC(4,2,2,4).run(runs)-1.0/6/3) <= tolerance : "Test 11";
// end::Tests[]
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment