CS 100: Lecture L8
February 18
public class upNdown { // Yields the number of turns required to reach // unity when the up-and-down sequence begins // at nStart. public static int turns(int nStart) { int n = nStart; int k = 0; while(n>1) { if(n%2==0) {n = n/2;} else {n = 3*n+1;} k++; } return k; } }
// Plot upNdown.turns import java.io.*; import java.awt.*; public class CUCSDrawing extends Frame { final int L = 50; // Horizontal coordinate of plot window's left edge. final int T = 50; // Vertical coordinate of plot window's top edge. final int W = 800; // The width of the plot window. final int H = 500; // The height of the plot window. final double Y = 200; // The y-value associated with the top of the plot window. final double S = H/Y; // Pixels per unit y-value. final int BASE = T+H; // Vertical coordinate of the plot windows bottom edge. public void paint(Graphics g) { // Draw a black plot window. g.fillRect(L,T,W,H); // Draw the upNdown "histogram" g.setColor(Color.magenta); int y; for(int x=1;x<=W;x++) { // Assign to y the number of turns required for starting value x. y = upNdown.turns(x); // Depict this value with a properly scaled vertical line segment. g.drawLine(L+x,BASE,L+x,(int)(BASE-y*S)); } // Draw 3 equally spaced horizontal gridlines. g.setColor(Color.cyan); for(int v=BASE-H/4;v>T;v=v-H/4) {g.drawLine(L,v,L+W,v);} } } public class L8 { public static void main(String args[]) { CUCSDrawing d = new CUCSDrawing(); d.resize(1000,600); d.move(0,75); d.setTitle("Up 'N Down"); d.show(); d.toFront(); } }