【算法 动态连通性】Percolation && PercolationStats 实现

普林斯顿·算法·Part 1·渗透实现

写在前面的话:
说实话,作为一个小白完全没去过Coursera听过英文课的我,绕了很多大弯,缺少关键信息的弯
没办法,抓不住语句重点,就很蠢。但我也要提出质疑,为什么不给出一个List注明 编程前必看?
对小白并不友好,甚至有点误导倾向,缺少视频辅导【针对于第一次做编程作业】
在编程的一开始,是最难的,对于小白的自信心建立来说。没有恰到好处的信息引导,是真的困难

一个人比较缓慢,大多数在于信息不全面、思维碰撞缺乏,在B站上也没有找到相关群体
故此,留一个群号,希望可以共同进步,相互监督,940774008

资源·前提

编程作业: Percolation
作业首页:https://www.coursera.org/learn/algorithms-part1/programming/Lhp5z/percolation
作业详情页:https://coursera.cs.princeton.edu/algs4/assignments/percolation/specification.php
作业FAQ页:https://coursera.cs.princeton.edu/algs4/assignments/percolation/faq.php
作业所需jar包:https://algs4.cs.princeton.edu/code/algs4.jar
Percolation可视化测试工程:https://coursera.cs.princeton.edu/algs4/assignments/percolation/percolation.zip
提交后评估指南:https://www.coursera.org/learn/algorithms-part1/resources/R2mre

作业所需引入的类:

import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
import edu.princeton.cs.algs4.WeightedQuickUnionUF;

FAQ必看内容:

  • Testing
提供了两个可用作大规模可视化痕迹的Cli。强烈建议使用它们来测试和调试 Percolation实现。
Visualization client. PercolationVisualizer.java 通过读取文件 进行测试
InteractiveVisualization client. InteractivePercolationVisualizer.java 通过读取鼠标输入 进行测试
  • Programming Tricks and Common Pitfalls
不要编写自己的联合查找数据结构。使用WeightedQuickUnionUF代替。【特么数据结构竟然是最难的】
Percolation类必须使用 WeightedQuickUnionUF 否则它将导致计时测试失败
  • Possible Progress Steps

在这里插入图片描述

Percolation.java

import edu.princeton.cs.algs4.WeightedQuickUnionUF;

public class Percolation {
    // 0 = closed, 1 = opened
    private byte[] grid;
    // the number of Opened-site
    private int count;
    private final int dimension;
    private final int virtualTop;

    // grid with top and bottom [0,n*n-1],[n*n]Top,[n*n+1]
    private final WeightedQuickUnionUF top;
    // grid with only top
    private final WeightedQuickUnionUF top2;

    // creates n-by-n grid, with all sites initially blocked
    public Percolation(int n) {
        if (n <= 0)
            throw new IllegalArgumentException();
        grid = new byte[n * n];
        top = new WeightedQuickUnionUF(n * n + 2);
        // only Top
        top2 = new WeightedQuickUnionUF(n * n + 1);
        count = 0;
        dimension = n;
        // virtualButton = virtualTop + 1
        virtualTop = dimension * dimension;
    }

    // opens the site (row, col) if it is not open already
    public void open(int row, int col) {
        isValid(row, col);
        if (!isOpen(row, col)) {
            int oneDS = dimensionReduction(row, col); // breakpoint·1
            grid[oneDS] = 1;
            count++;
			
			// 前置设置条件,而不是与上下左右二选一
            // if the firstRow,union 0 <=> OneDimensionalSite
            if (row == 1) {
                top.union(virtualTop, oneDS);
                top2.union(virtualTop, oneDS);
            }
            // if the lastRow,union last <=> ODSite
            if (row == dimension) {
                top.union(virtualTop + 1, oneDS);
            }

            // up
            if (row > 1 && isOpen(row - 1, col)) {
                top.union(oneDS, dimensionReduction(row - 1, col));
                top2.union(oneDS, dimensionReduction(row - 1, col));
            }
            // down
            if (row < dimension && isOpen(row + 1, col)) {
                top.union(oneDS, dimensionReduction(row + 1, col));
                top2.union(oneDS, dimensionReduction(row + 1, col));
            }
            // left
            if (col > 1 && isOpen(row, col - 1)) {
                top.union(oneDS, dimensionReduction(row, col - 1));
                top2.union(oneDS, dimensionReduction(row, col - 1));
            }
            // right
            if (col < dimension && isOpen(row, col + 1)) {
                top.union(oneDS, dimensionReduction(row, col + 1));
                top2.union(oneDS, dimensionReduction(row, col + 1));
            }
        }
    }


    // is the site (row, col) open?
    public boolean isOpen(int row, int col) {
        isValid(row, col);
        return grid[dimensionReduction(row, col)] == 1;
    }

    // is the site (row, col) full?
    public boolean isFull(int row, int col) {
        if (isOpen(row, col))
            return top.find(dimensionReduction(row, col)) == virtualTop
                    && top2.find(dimensionReduction(row, col)) == virtualTop;
        return false;
    }

    // returns the number of open sites
    public int numberOfOpenSites() {
        return count;
    }

    // does the system percolate?
    public boolean percolates() {
        return top.find(virtualTop) == top.find(virtualTop + 1);
    }


    private void isValid(int row, int col) {
        if (row <= 0 || row > dimension || col <= 0 || col > dimension)
            throw new IllegalArgumentException();
    }

    private int dimensionReduction(int row, int col) {
        return (row - 1) * dimension + (col - 1);
    }

    // test client (optional)
    /* public static void main(String[] args) {

    } */
}

注:PercolationVisualizer.java 断点 打到 80行 draw(perc,n);

PercolationStats.java

import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;

public class PercolationStats {

    private double mean;
    private double stddev;
    private double[] trialsResult;
    private double confidenceLow;
    private double confidenceHigh;

    // perform independent trials on an n-by-n grid
    public PercolationStats(int dimension, int trials) {
        if (dimension <= 0 || trials <= 0)
            throw new IllegalArgumentException();
        if (dimension == 1) {
            mean = 1;
            stddev = Double.NaN;
            confidenceLow = Double.NaN;
            confidenceHigh = Double.NaN;
        } else {
            trialsResult = new double[trials];
            for (int i = 0; i < trials; i++) {
                trialsResult[i] = oneTrial(dimension);
            }
            mean = StdStats.mean(trialsResult);
            stddev = StdStats.stddev(trialsResult);
            double diff = (1.96 * stddev) / Math.sqrt(trials);
            confidenceLow = mean - diff;
            confidenceHigh = mean + diff;
        }

    }

    // sample mean of percolation threshold
    public double mean() {
        return mean;
    }

    // sample standard deviation of percolation threshold
    public double stddev() {
        return stddev;
    }

    // low endpoint of 95% confidence interval
    public double confidenceLo() {
        return confidenceLow;
    }

    // high endpoint of 95% confidence interval
    public double confidenceHi() {
        return confidenceHigh;
    }

    // test client (see below)
    public static void main(String[] args) {
        int dimension = Integer.parseInt(args[0]);
        int trials = Integer.parseInt(args[1]);
        PercolationStats ps = new PercolationStats(dimension, trials);
        edu.princeton.cs.algs4.StdOut.println("mean                    = " + ps.mean());
        edu.princeton.cs.algs4.StdOut.println("stddev                  = " + ps.stddev());
        edu.princeton.cs.algs4.StdOut
                .println("95% confidence interval = [" + ps.confidenceLo() + ", " + ps.confidenceHi() + "]");
    }

    private double oneTrial(int dimension) {
        Percolation percolation = new Percolation(dimension);
        while (!percolation.percolates()) {
            int row = StdRandom.uniform(dimension) + 1;
            int col = StdRandom.uniform(dimension) + 1;
            if (!percolation.isOpen(row, col)) {
                percolation.open(row, col);
            }
        }
        return (double) percolation.numberOfOpenSites() / (dimension * dimension);
    }
}

评估结果

有时间再改进。主要目的过完整个课程

See the Assessment Guide for information on how to interpret this report.

ASSESSMENT SUMMARY

Compilation:  PASSED
API:          PASSED

Spotbugs:     PASSED
PMD:          PASSED
Checkstyle:   PASSED

Correctness:  23/33 tests passed
Memory:       8/8 tests passed
Timing:       20/20 tests passed

Aggregate score: 81.82%
[Compilation: 5%, API: 5%, Spotbugs: 0%, PMD: 0%, Checkstyle: 0%, Correctness: 60%, Memory: 10%, Timing: 20%]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值