-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPercolationStats.java
98 lines (85 loc) · 2.37 KB
/
PercolationStats.java
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
public class PercolationStats {
private Percolation perc;
private int T;
private double mean;
private double stdDev;
private double confLow;
private double confHigh;
public PercolationStats(int N, int t) // perform T independent experiments on an N-by-N grid
{
if (N <= 0 || t <= 0)
{
throw new IllegalArgumentException();
}
T = t;
perc = new Percolation(N);
int totalOpenSites = 0;
int[] os = new int[T];
//perform experiments
for (int i = 0; i < T; i++)
{
//single experiment
perc = new Percolation(N);
int openSites = 0;
while(!perc.percolates())
{
int k = StdRandom.uniform(N-i) + 1;
int j = StdRandom.uniform(N-i) + 1;
System.out.println(k);
System.out.println(j);
if (!perc.isOpen(k, j))
{
perc.open(k, j);
openSites += 1;
}
os[i] = openSites;
totalOpenSites += openSites;
}
}// end experiments
mean = totalOpenSites/T;
// std dev
double sum = 0;
for (int i = 0; i < T; i++)
{
sum += Math.pow(os[i] - mean, 2);
}
double stdDevSq = sum/(T-1);
stdDev = Math.pow(stdDevSq, 0.5);
}//ctor
public double mean() // sample mean of percolation threshold
{
return mean;
}
public double stddev() // sample standard deviation of percolation threshold
{
return stdDev;
}
public double confidenceLo() // low endpoint of 95% confidence interval
{
return confLow;
}
public double confidenceHi() // high endpoint of 95% confidence interval
{
return confHigh;
}
public static void main(String[] args) // test client (described below)
{
// StdOut.println(" Hello");
// int N = StdIn.readInt();
// WeightedQuickUnionUF uf = new WeightedQuickUnionUF(N);
// while (!StdIn.isEmpty()) {
// int p = StdIn.readInt();
// int q = StdIn.readInt();
// if (uf.connected(p, q)) continue;
// uf.union(p, q);
// StdOut.println(p + " " + q);
// }
// StdOut.println(uf.count() + " components");
int T = 3;
int N = 4;
PercolationStats p = new PercolationStats(T, N);
StdOut.print("mean = "); StdOut.println(p.mean());
StdOut.print("stddev = "); StdOut.println(p.stddev());
StdOut.print("95% confidence interval = "); StdOut.println(p.confidenceLo()+", "+ p.confidenceHi());
}//main
}