本系列博客習(xí)題來自《算法(第四版)》,算是本人的讀書筆記,如果有人在讀這本書的,歡迎大家多多交流。為了方便討論,本人新建了一個(gè)微信群(算法交流),想要加入的,請?zhí)砑游业奈⑿盘?hào):zhujinhui207407 謝謝。另外,本人的個(gè)人博客 http://www.kyson.cn 也在不停的更新中,歡迎一起討論

知識(shí)點(diǎn)
- 計(jì)數(shù)器
- 點(diǎn)的繪制
題目
1.2.10 編寫一個(gè)類 VisualCounter,支持加一和減一操作。它的構(gòu)造函數(shù)接受兩個(gè)參數(shù) N 和 max,其中 N 指定了操作的最大次數(shù), max 指定了計(jì)數(shù)器的最大絕對值。作為副作用,用圖像顯示每次計(jì)數(shù)器變化后的值。
1.2.10 Develop a class VisualCounter that allows both increment and decrement operations. Take two arguments N and max in the constructor, where N specifies the maximum number of operations and max specifies the maximum absolute value for the counter. As a side effect, create a plot showing the value of the counter each time its tally changes.
public class VisualCounter {
private long N;
private double total;
public VisualCounter(long trails, double max) {
StdDraw.setXscale(0, trails);
StdDraw.setYscale(-max, max);
StdDraw.setPenRadius(.005f);
}
public void increment() {
N++;
total ++;
StdDraw.setPenColor(StdDraw.DARK_GRAY);
StdDraw.point(N, total);
}
public void decrement() {
N++;
total --;
StdDraw.setPenColor(StdDraw.DARK_GRAY);
StdDraw.point(N, total);
}
public static void main(String[] args) {
VisualCounter counter = new VisualCounter(300, 150.0);
for (int i = 0; i < 10000; i++)
if (StdRandom.random() > 0.5) {
counter.increment();;
}else {
counter.decrement();;
}
StdOut.println(counter);
}
}
代碼索引
視頻講解
廣告
我的首款個(gè)人開發(fā)的APP壁紙寶貝上線了,歡迎大家下載。
本人所有簡書的算法文章已經(jīng)移入小專欄:算法四習(xí)題詳解,歡迎大家訂閱