要求:能进行±1的可视化counter
  1. import edu.princeton.cs.algs4.StdDraw;
  2. import edu.princeton.cs.algs4.StdRandom;
  3. public class Ex1_1_10 {
  4. public static class VisualCounter{
  5. private int times = 0;
  6. private int count = 0;
  7. private int max;
  8. public VisualCounter(int N, int max){
  9. this.max = max;
  10. StdDraw.setXscale(0,N);
  11. StdDraw.setYscale(-max,max);
  12. StdDraw.setPenRadius(.005);
  13. }
  14. public void increment(){
  15. count++;
  16. times++;
  17. if(count > max) count = max;
  18. StdDraw.point(times,count);
  19. }
  20. public void reduction(){
  21. times++;
  22. count--;
  23. if(count < -max) count = -max;
  24. StdDraw.point(times,count);
  25. }
  26. }
  27. public static void main(String[] args){
  28. int N = Integer.parseInt(args[0]);
  29. int max = Integer.parseInt(args[1]);
  30. VisualCounter counter = new VisualCounter(N,max);
  31. for(int i=0; i<N; i++){
  32. if(StdRandom.bernoulli(0.5)){
  33. counter.increment();
  34. }else{
  35. counter.reduction();
  36. }
  37. }
  38. }
  39. }

结果(N = 10000, max = 100)

Ex1_2_10 - 图1