-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrison.java
More file actions
65 lines (53 loc) · 1.66 KB
/
Prison.java
File metadata and controls
65 lines (53 loc) · 1.66 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
65
/***
* The class Prison and its "cells" models a one-dimensional cellular automata.
*/
public class Prison {
private boolean[] schedule;
private int calculateScore(int cellNumber) {
int score = 0;
if (schedule[cellNumber]) {
score += 2;
}
if (cellNumber > 0 && schedule[cellNumber - 1]) {
score += 4;
}
if (cellNumber < schedule.length - 1 && schedule[cellNumber + 1]) {
score += 1;
}
return score;
}
private boolean mustInspect(int score) {
return ruleTable[score];
}
public void updateSchedule() {
boolean[] replacement = new boolean[schedule.length];
for (int i = 0; i < schedule.length; i++) {
replacement[i] = mustInspect(calculateScore(i));
}
schedule = replacement;
}
private boolean[] ruleTable; // used by mustInspect
public Prison(int numCells, int rule) {
schedule = new boolean[numCells];
schedule[schedule.length/2] = true; // seed the middle cell
ruleTable = new boolean[8];
for (int i = 0; i < ruleTable.length; i++) {
ruleTable[i] = ((rule >> i) & 1) == 1;
}
}
public void randomizeSchedule() {
for (int i = 0; i < schedule.length; i++) {
schedule[i] = Math.random() > 0.5;
}
}
public String toString() {
return toString('*', '.');
}
public String toString(char trueChar, char falseChar) {
String result = "";
for (int i = 0; i < schedule.length; i++) {
result+=schedule[i]? trueChar : falseChar;
}
return result;
}
}