-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPercolation.java
More file actions
337 lines (267 loc) · 7.89 KB
/
Copy pathPercolation.java
File metadata and controls
337 lines (267 loc) · 7.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS info.picocli:picocli:4.7.5
//SOURCE ./percolation/GridSites.java
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;
import java.util.concurrent.Callable;
// Main Class
@Command(name = "percolation", mixinStandardHelpOptions = true, version = "algo 0.1", description = "algo made with jbang")
class Questionaire implements Callable<Integer> {
@Parameters(index = "0", defaultValue = "200")
static String gridSize;
@Parameters(index = "1", defaultValue = "100")
static String T;
@Parameters(index = "2", defaultValue = "0")
static String totalOpenSites;
// function to convert a string to an integer
public static int stringToInt(String str) {
try {
return Integer.parseInt(str);
}
catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid integer: " + e.getMessage());
return 0;
}
}
public static void main(String... args) {
int exitCode = new CommandLine(new Questionaire()).execute(args);
System.exit(exitCode);
}
@Override
public Integer call() throws Exception {
PercolationTest.start(stringToInt(gridSize), stringToInt(T), stringToInt(totalOpenSites));
return 0;
}
}
// tests the perculation
class PercolationTest {
public static void start(
int gridSizeParam,
int triesParam,
int totalOpenSitesParam) {
int gridSize = gridSizeParam;
int T = triesParam;
int totalOpenSites = totalOpenSitesParam;
double[] thresholds = new double[T];
GridSitesGenerator gridGenerator = new GridSitesGenerator(gridSize);
Percolation percolation = new Percolation(gridGenerator);
for (int i = 0; i < T; i++) {
gridGenerator = new GridSitesGenerator(gridSize);
percolation = new Percolation(gridGenerator);
percolation.create(gridSize);
while (!percolation.percolates()) {
int row = (int) (Math.random() * gridSize);
int col = (int) (Math.random() * gridSize);
if (!percolation.isOpen(row, col)) {
percolation.open(row, col);
totalOpenSites++;
}
}
// simulation reset
thresholds[i] = (double) totalOpenSites / (gridSize * gridSize);
totalOpenSites = 0;
}
// setter for the required solutions
Stats stats = new Stats();
double averageThreshold = stats.mean(thresholds);
double stddev = stats.stddev(thresholds);
double confidenceLo = stats.confidenceLo(thresholds);
double confidenceHi = stats.confidenceHi(thresholds);
gridGenerator.printGrid();
System.out.println();
//result displays on the terminal
System.out.println("Mean percolation threshold: " + averageThreshold);
System.out.println("Stddev: " + stddev);
System.out.println("95% confidence interval: [" + confidenceLo + ", " + confidenceHi + "]");
}
}
class Percolation implements PercolationBase {
private GridSitesGenerator gridGenerator;
private WeightedQuickUnion wqu;
private int gridSize;
public Percolation(GridSitesGenerator gridGenerator) {
this.gridGenerator = gridGenerator;
}
// includes 2 viritual nodes as openings on top and bottom
@Override
public void create(int n) {
gridSize = n;
wqu = new WeightedQuickUnion(n * n + 2);
}
@Override
public void open(int row, int col) {
gridGenerator.open(row, col);
// add 1 to validate the top virtual node
int siteIndex = row * gridSize + col + 1;
// Connect to open neighbors and virtual nodes
if (row > 0 && isOpen(row - 1, col)) {
wqu.union(siteIndex, (row - 1) * gridSize + col + 1);
}
if (row < gridSize - 1 && isOpen(row + 1, col)) {
wqu.union(siteIndex, (row + 1) * gridSize + col + 1);
}
if (col > 0 && isOpen(row, col - 1)) {
wqu.union(siteIndex, row * gridSize + (col - 1) + 1);
}
if (col < gridSize - 1 && isOpen(row, col + 1)) {
wqu.union(siteIndex, row * gridSize + (col + 1) + 1);
}
if (row == 0) {
// connects on the virtual node on top
wqu.union(siteIndex, 0);
}
wqu.union(siteIndex, gridSize * gridSize + 1);
// connects on the virtual node on bottom
if (row == gridSize - 1) {
}
}
@Override
public boolean isFull(int row, int col) {
int siteIndex = row * gridSize + col + 1;
// checker if it is connected on the top virtual node
return wqu.connected(siteIndex, 0);
}
@Override
public int numberOfOpenSites() {
return gridGenerator.getNumberOfOpenSites();
}
@Override
public boolean percolates() {
// checker if both the top and bottom virtual nodes are connected
return wqu.connected(0, gridSize * gridSize + 1);
}
@Override
public boolean isOpen(int row, int col) {
return gridGenerator.isOpen(row, col);
}
};
// solutions for mean, sd, confidence level
class Stats {
public double mean(double[] numbers) {
double sum = 0;
for (double num : numbers) {
sum += num;
}
return sum / numbers.length;
}
public double stddev(double[] numbers) {
double mean = mean(numbers);
double sum = 0;
for (double num : numbers) {
sum += Math.pow(num - mean, 2);
}
return Math.sqrt(sum / (numbers.length - 1));
}
public double confidenceLo(double[] numbers) {
double mean = mean(numbers);
double stddev = stddev(numbers);
return mean - 1.96 * stddev / Math.sqrt(numbers.length);
}
public double confidenceHi(double[] numbers) {
double mean = mean(numbers);
double stddev = stddev(numbers);
return mean + 1.96 * stddev / Math.sqrt(numbers.length);
}
}
// displays the grid on the terminal
class GridSitesGenerator {
private int[][] grid;
private int size;
public GridSitesGenerator(int size) {
this.size = size;
grid = new int[size][size];
for (int i = 0; i < size; i++) {
grid[i] = new int[size];
}
}
public void open(int row, int col) {
grid[row][col] = 1;
}
public boolean isOpen(int row, int col) {
return grid[row][col] == 1;
}
public boolean isFull(int row, int col) {
return grid[row][col] == 2;
}
public void fill(int row, int col) {
grid[row][col] = 2;
}
public int getSize() {
return size;
}
public int[][] getGrid() {
return grid;
}
public void printGrid() {
System.out.println();
for (int i = 0; i < size; i++) {
System.out.println();
for (int j = 0; j < size; j++) {
System.out.print(grid[i][j] + " ");
}
}
}
public int getNumberOfOpenSites() {
int count = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (grid[i][j] == 1) {
count++;
}
}
}
return count;
}
}
// the algorithm Monte Carlo simulation
class WeightedQuickUnion {
private int[] id;
private int[] sz;
public WeightedQuickUnion(int N) {
id = new int[N];
sz = new int[N];
for (int i = 0; i < N; i++) {
id[i] = i;
sz[i] = 1;
}
}
private int root(int i) {
while (i != id[i]) {
// path compression
id[i] = id[id[i]];
i = id[i];
}
return i;
}
public boolean connected(int p, int q) {
return root(p) == root(q);
}
public void union(int p, int q) {
int i = root(p);
int j = root(q);
if (i == j)
return;
if (sz[i] < sz[j]) {
id[i] = j;
sz[j] += sz[i];
} else {
id[j] = i;
sz[i] += sz[j];
}
}
}
interface PercolationBase {
// creates n-by-n grid, with all sites initially blocked
void create(int n);
// opens the site (row, col) if it is not open already
void open(int row, int col);
// checks ig the site on row and column are open
boolean isOpen(int row, int col);
// checks ig the site on row and column are full
boolean isFull(int row, int col);
// returns the amount of sites that are open
int numberOfOpenSites();
// checks if the system percolates
boolean percolates();
}