改了好久的代码percolation,还是在小伙伴的帮助下得以通过得到了92分。还是代码能力好差。总结了一下出错的地方。
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
private double[] thresholds;
public PercolationStats(int n, int trials) {
if (n <= 0 || trials <= 0)
throw new IllegalArgumentException();
thresholds = new double[trials];
for (int i = 0; i < trials; i++) {
int count = 0;
Percolation percolation = new Percolation(n);
while(true) {
count++;
while (true)
{
int row = StdRandom.uniform(1, n + 1);
int column = StdRandom.uniform(1, n + 1);
if (percolation.isOpen(row, column))
continue;
else {
percolation.open(row, column);
break;
}
}
if(percolation.percolates()) {
thresholds[i] = (double) count / ((double)n * (double)n);
break;
}
}
}
}
public double mean() {
return StdStats.mean(this.thresholds);
}
public double stddev() {
return StdStats.stddev(this.thresholds);
}
public double confidenceLo() {
return (mean() - 1.96* stddev() / Math.sqrt(thresholds.length));
}
public double confidenceHi() {
return (mean() + 1.96 * stddev() / Math.sqrt(thresholds.length));
}
public static void main(String[] args) {
int N = StdIn.readInt();
int T = StdIn.readInt();
PercolationStats pers = new PercolationStats(N, T);
StdOut.println("mean = "+pers.mean());
StdOut.println("stddev = "+pers.stddev());
StdOut.println("95% confidence interval = ["+pers.confidenceLo()+", "+pers.confidenceHi()+"]");
}
}
这两个while(true)的用法理解出现了偏差,也作为一个循环的使用,在条件不满足时则有break语句跳出当前死循环。
这篇博客讲述了作者在实现Percolation算法时遇到的问题和解决方案,通过多次试验计算了阈值的平均值、标准差以及95%置信区间。文章重点在于对双重while循环的理解和使用,以及如何在满足特定条件时跳出循环。
500

被折叠的 条评论
为什么被折叠?



