代码percolation

来源:互联网 发布:端口类型有几种 编辑:程序博客网 时间:2024/05/19 10:35

改了好久的代码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语句跳出当前死循环。


原创粉丝点击