中文版238页图3.1.3演示了SequentialSearchST算法中每次写入单词数量(put方法中)时需要进行的比较次数,也就是此算法的成本,但书中没有生成此图的代码,下面是我自己的实现(第一个是新增的类,后两个是修改的类):
package edu.princeton.cs.algs4; public class VisualAccumulator { private double total; private int N; public VisualAccumulator(int trials, double max) { StdDraw.setXscale(0, trials); StdDraw.setYscale(0, max); StdDraw.setPenRadius(.005); } public void addDataValue(double val) { N++; total += val; StdDraw.setPenColor(StdDraw.DARK_GRAY); StdDraw.point(N, val); StdDraw.setPenColor(StdDraw.RED); StdDraw.point(N, total / N); StdOut.println("Red point value:" + total / N);// 平均比较次数 } public double mean() { return total / N; } @Override public String toString() { return "Mean (" + N + " values): " + String.format("%7.5f", mean()); } public static void main(String[] args) { int T = 300; VisualAccumulator a = new VisualAccumulator(T, 1.0); for (int t = 0; t < T; t++) { a.addDataValue(StdRandom.random()); } StdOut.println(a); } }
public class SequentialSearchST
public class FrequencyCounter {
public static void main(String[] args) {
StdIn2.setInputFile("data/tale.txt");
int distinct = 0, words = 0;
int minlen = 8; // this is the first parameter
SequentialSearchST
以上VisualAccumulator是完整的类,SequentialSearchST只写出了新增的属性compareTimes及其get方法,和修改后的put和main方法;FrequencyCounter类中修改后的main方法,