import element.*; import java.util.Random; public class Functions { public static int rand(int low, int high, Random gen) // pre: low <= high // post: returns uniformly random value v, low <= v <= high { return (Math.abs(gen.nextInt())%(high-low+1))+low; } public static int square(int n) // post: returns the square of the value n { return n*n; } public static int sumOfSquares(int n) // pre: n >= 0 // post: returns the sum of squares of values between 0 and n { int sum = 0; // intermediate result int i; for (i = 1; i <= n; i++) { sum = sum + square(i); // calls our square function } return sum; } public static Pt opposite(DrawingWindow d, Pt p) // pre: p is a valid point, d a valid window // post: returns the point that is opposite of p in d { int windowRight = d.bounds().right(); int windowBottom = d.bounds().bottom(); Pt oppositeP = new Pt(windowRight-p.x(), windowBottom-p.y()); return oppositeP; } public static void mirror() { DrawingWindow d = new DrawingWindow(); d.awaitMousePress(); // drawing starts with mouse press Pt current, next; // points current = d.getMouse(); // initial location while (d.mousePressed()) { next = d.getMouse(); // get next mouse position d.moveTo(current); // draw the "right" image d.lineTo(next); d.moveTo(opposite(d,current)); // draw mirrored segment d.lineTo(opposite(d,next)); current = next; } } public static void main(String args[]) { ConsoleWindow c = new ConsoleWindow(); DrawingWindow d = new DrawingWindow(); int i, count=0; Random gen; c.out.println("Square of 3 is (9?): "+square(3)); c.out.println("Sum of squares from 1 to 10 is (?): "+sumOfSquares(10)); Pt p = new Pt(50,70); c.out.println("Point opposite of point "+p+" is "+opposite(d,p)); gen = new Random(); for (i = 0; i < 1000; i++) { if (rand(42,141,gen) == 42) count++; } c.out.println(count*100.0/1000.0+"% of 100 sided die roles are zero."); mirror(); System.exit(0); } }