-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrand.java
More file actions
64 lines (53 loc) · 1.89 KB
/
rand.java
File metadata and controls
64 lines (53 loc) · 1.89 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.Random;
public class RandomizeProblemsAndAnswers {
/* The number of problems (in) */
int nprob;
/* For each i in 0..numProblems - 1, the number of answers to problem i (in). */
int[] numAnswers;
/* The random number generator (in) */
Random rand;
/* Permutation of problem IDs (out) */
int[] probPerm;
/* A permutation for each problem (out) */
int[][] answerPerms;
/* Constructs new instance from given fields. Sets fields only, does nothing else. */
public RandomizeProblemsAndAnswers(int nprob, int[] numAnswers, Random rand) {
this.nprob = nprob;
this.numAnswers = numAnswers;
this.rand = rand;
}
/* Constructs the probPerm. */
public void execute() {
this.probPerm = new int[nprob];
for (int i = 0; i < nprob; i++)
probPerm[i] = i;
for (int i = nprob - 1; i >= 0; i--) {
int j = rand.nextInt(i + 1);
if (i != j) {
int t = probPerm[i];
probPerm[i] = probPerm[j];
probPerm[j] = t;
}
}
// Construct random permutations for each problem
answerPerms = new int[nprob][];
for (int i = 0; i < nprob; i++) {
answerPerms[i] = new int[numAnswers[i]];
randomizeProblem(i);
}
}
/* Constructs random permutation for problem pid, writing to answerPerms[pid][*]. */
private void randomizeProblem(int pid) {
int nanswer = numAnswers[pid];
for (int i = 0; i < nanswer; i++)
answerPerms[pid][i] = i;
for (int i = nanswer - 1; i >= 0; i--) {
int j = rand.nextInt(i + 1);
if (i != j) {
int t = answerPerms[pid][i];
answerPerms[pid][i] = answerPerms[pid][j];
answerPerms[pid][j] = t;
}
}
}
}