要求:能进行±1的可视化counter
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdRandom;
public class Ex1_1_10 {
public static class VisualCounter{
private int times = 0;
private int count = 0;
private int max;
public VisualCounter(int N, int max){
this.max = max;
StdDraw.setXscale(0,N);
StdDraw.setYscale(-max,max);
StdDraw.setPenRadius(.005);
}
public void increment(){
count++;
times++;
if(count > max) count = max;
StdDraw.point(times,count);
}
public void reduction(){
times++;
count--;
if(count < -max) count = -max;
StdDraw.point(times,count);
}
}
public static void main(String[] args){
int N = Integer.parseInt(args[0]);
int max = Integer.parseInt(args[1]);
VisualCounter counter = new VisualCounter(N,max);
for(int i=0; i<N; i++){
if(StdRandom.bernoulli(0.5)){
counter.increment();
}else{
counter.reduction();
}
}
}
}
结果(N = 10000, max = 100)