001package algs12; 002import stdlib.*; 003/* *********************************************************************** 004 * Compilation: javac Counter.java 005 * Execution: java Counter N T 006 * Dependencies: StdRandom.java StdOut.java 007 * 008 * A mutable data type for an integer counter. 009 * 010 * The test clients create N counters and performs T increment 011 * operations on random counters. 012 * 013 * % java Counter 6 600000 014 * 0: 99870 015 * 1: 99948 016 * 2: 99738 017 * 3: 100283 018 * 4: 100185 019 * 5: 99976 020 * 021 *************************************************************************/ 022 023public class Counter implements Comparable<Counter> { 024 025 private final String name; // counter name 026 private int count; // current value 027 028 // create a new counter 029 public Counter(String id) { 030 name = id; 031 } 032 033 // increment the counter by 1 034 public void increment() { 035 count++; 036 } 037 038 // return the current count 039 public int tally() { 040 return count; 041 } 042 043 // return a string representation of this counter 044 public String toString() { 045 return count + " " + name; 046 } 047 048 // compare two Counter objects based on their count 049 public int compareTo(Counter that) { 050 if (this.count < that.count) return -1; 051 else if (this.count > that.count) return +1; 052 else return 0; 053 } 054 055 056 // test client 057 public static void main(String[] args) { 058 args = new String[] { "2", "10"}; 059 060 int N = Integer.parseInt(args[0]); 061 int T = Integer.parseInt(args[1]); 062 063 // create N counters 064 Counter[] hits = new Counter[N]; 065 for (int i = 0; i < N; i++) { 066 hits[i] = new Counter("counter" + i); 067 } 068 069 // increment T counters at random 070 for (int t = 0; t < T; t++) { 071 hits[StdRandom.uniform(N)].increment ();; 072 } 073 074 // print results 075 for (int i = 0; i < N; i++) { 076 StdOut.println(hits[i]); 077 } 078 } 079}