/************************************************************************* * Compilation: javac Average.java * Execution: java Average < data.txt * Dependencies: StdIn.java StdOut.java * * Reads in a sequence of real numbers, and computes their average. * * % java Average * 10.0 5.0 6.0 * 3.0 7.0 32.0 ** Average is 10.5 * Note signifies the end of file on Unix. * On windows use . * *************************************************************************/ public class Average { public static void main(String[] args) { int count = 0; // number input values double sum = 0.0; // sum of input values // read data and compute statistics while (!StdIn.isEmpty()) { double value = StdIn.readDouble(); sum += value; count++; } // compute the average double average = sum / count; // print results StdOut.println("Average is " + average); } }
Showing posts with label Elements Of Programming. Show all posts
Showing posts with label Elements Of Programming. Show all posts
Thursday, 25 October 2012
Average.java
Labels:
Elements Of Programming,
Java
TwentyQuestions.java
/************************************************************************* * Compilation: javac TwentyQuestions.java * Execution: java TwentyQuestions * Dependencies StdIn.java * * % java TwentyQuestions * I'm thinking of a number between 1 and 1,000,000 * What's your guess? 500000 * Too high * What's your guess? 250000 * Too low * What's your guess? 375000 * Too high * What's your guess? 312500 * Too high * What's your guess? 300500 * Too low * ... * *************************************************************************/ public class TwentyQuestions { public static void main(String[] args) { // Generate a number and answer questions // while the user tries to guess the value. int N = 1 + (int) (Math.random() * 1000000); StdOut.print("I'm thinking of a number "); StdOut.println("between 1 and 1,000,000"); int m = 0; while (m != N) { // Solicit one guess and provide one answer StdOut.print("What's your guess? "); m = StdIn.readInt(); if (m == N) StdOut.println("You win!"); if (m < N) StdOut.println("Too low "); if (m > N) StdOut.println("Too high"); } } }
Labels:
Elements Of Programming,
Java
RandomSeq.java
/************************************************************************* * Compilation: javac RandomSeq.java * Execution: java RandomSeq N * * Prints N numbers between 0 and 1. * * % java RandomSeq 5 * 0.1654760343787165 * 0.6212262060326124 * 0.631755596883274 * 0.4165639935584283 * 0.4603525361488371 * *************************************************************************/ public class RandomSeq { public static void main(String[] args) { // command-line argument int N = Integer.parseInt(args[0]); // generate and print N numbers between 0 and 1 for (int i = 0; i < N; i++) { System.out.println(Math.random()); } } }
Labels:
Elements Of Programming,
Java
SelfAvoidingWalk.java
/************************************************************************* * Compilation: javac SelfAvoidingWalk.java * Execution: java SelfAvoidingWalk N T * * Generate T self-avoiding walks of length N. * Report the fraction of time the random walk is non self-intersecting. * *************************************************************************/ public class SelfAvoidingWalk { public static void main(String[] args) { int N = Integer.parseInt(args[0]); // lattice size int T = Integer.parseInt(args[1]); // number of trials int deadEnds = 0; // trials resulting in a dead end // simulate T self-avoiding walks for (int t = 0; t < T; t++) { boolean[][] a = new boolean[N][N]; // intersections visited int x = N/2, y = N/2; // current position // repeatedly take a random step, unless you've already escaped while (x > 0 && x < N-1 && y > 0 && y < N-1) { // dead-end, so break out of loop if (a[x-1][y] && a[x+1][y] && a[x][y-1] && a[x][y+1]) { deadEnds++; break; } // mark (x, y) as visited a[x][y] = true; // take a random step to unvisited neighbor double r = Math.random(); if (r < 0.25) { if (!a[x+1][y]) x++; } else if (r < 0.50) { if (!a[x-1][y]) x--; } else if (r < 0.75) { if (!a[x][y+1]) y++; } else if (r < 1.00) { if (!a[x][y-1]) y--; } } } System.out.println(100*deadEnds/T + "% dead ends"); } }
Labels:
Elements Of Programming,
Java
RangeFilter.java
/************************************************************************* * Compilation: javac RangeFilter.java * Execution: java RangeFilter lo hi < input.txt * Dependencies: StdIn.java * * Read in a sequence of integers from standard input and print * out those values between lo and hi. * *************************************************************************/ public class RangeFilter { public static void main(String[] args) { // read in two command-line arguments int lo = Integer.parseInt(args[0]); int hi = Integer.parseInt(args[1]); // repeat as long as there's more input to read in while (!StdIn.isEmpty()) { // read in the next integer int t = StdIn.readInt(); // print out the given integer if it's between lo and hi if (t >= lo && t <= hi) { StdOut.print(t + " "); } } StdOut.println(); } }
Labels:
Elements Of Programming,
Java
PlotFilter.java
/************************************************************************* * Compilation: javac PlotFilter.java * Execution: java PlotFilter < input.txt * Dependencies: StdDraw.java StdIn.java * * % java PlotFilter < USA.txt * * Datafiles: http://www.cs.princeton.edu/IntroProgramming/15inout/USA.txt * *************************************************************************/ public class PlotFilter { public static void main(String[] args) { // read in bounding box and rescale double x0 = StdIn.readDouble(); double y0 = StdIn.readDouble(); double x1 = StdIn.readDouble(); double y1 = StdIn.readDouble(); StdDraw.setXscale(x0, x1); StdDraw.setYscale(y0, y1); // turn on animation mode to defer displaying all of the points // StdDraw.show(0); // plot points, one at a time while (!StdIn.isEmpty()) { double x = StdIn.readDouble(); double y = StdIn.readDouble(); StdDraw.point(x, y); } // display all of the points now // StdDraw.show(0); } }
Labels:
Elements Of Programming,
Java
BouncingBall.java
/************************************************************************* * Compilation: javac BouncingBall.java * Execution: java BouncingBall * Dependencies: StdDraw.java * * Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1). * * % java BouncingBall * *************************************************************************/ public class BouncingBall { public static void main(String[] args) { // set the scale of the coordinate system StdDraw.setXscale(-1.0, 1.0); StdDraw.setYscale(-1.0, 1.0); // initial values double rx = 0.480, ry = 0.860; // position double vx = 0.015, vy = 0.023; // velocity double radius = 0.05; // radius // main animation loop while (true) { // bounce off wall according to law of elastic collision if (Math.abs(rx + vx) > 1.0 - radius) vx = -vx; if (Math.abs(ry + vy) > 1.0 - radius) vy = -vy; // update position rx = rx + vx; ry = ry + vy; // clear the background StdDraw.setPenColor(StdDraw.GRAY); StdDraw.filledSquare(0, 0, 1.0); // draw ball on the screen StdDraw.setPenColor(StdDraw.BLACK); StdDraw.filledCircle(rx, ry, radius); // display and pause for 20 ms StdDraw.show(20); } } }
PlayThatTune.java
/************************************************************************* * Compilation: javac PlayThatTune.java * Execution: java PlayThatTune < input.txt * Dependencies: StdAudio.java StdAudio.java * * This is a data-driven program that plays pure tones from * the notes on the chromatic scale, specified on standard input * by their distance from concert A. * * % java PlayThatTune < elise.txt * * * Data files * ---------- * http://www.cs.princeton.edu/introcs/21function/elise.txt * http://www.cs.princeton.edu/introcs/21function/99luftballons.txt * http://www.cs.princeton.edu/introcs/21function/freebird.txt * http://www.cs.princeton.edu/introcs/21function/Ascale.txt * http://www.cs.princeton.edu/introcs/21function/National_Anthem.txt * http://www.cs.princeton.edu/introcs/21function/looney.txt * http://www.cs.princeton.edu/introcs/21function/StairwayToHeaven.txt * http://www.cs.princeton.edu/introcs/21function/entertainer.txt * http://www.cs.princeton.edu/introcs/21function/old-nassau.txt * http://www.cs.princeton.edu/introcs/21function/arabesque.txt * http://www.cs.princeton.edu/introcs/21function/firstcut.txt * http://www.cs.princeton.edu/introcs/21function/tomsdiner.txt * *************************************************************************/ public class PlayThatTune { public static void main(String[] args) { // repeat as long as there are more integers to read in while (!StdIn.isEmpty()) { // read in the pitch, where 0 = Concert A (A4) int pitch = StdIn.readInt(); // read in duration in seconds double duration = StdIn.readDouble(); // build sine wave with desired frequency double hz = 440 * Math.pow(2, pitch / 12.0); int N = (int) (StdAudio.SAMPLE_RATE * duration); double[] a = new double[N+1]; for (int i = 0; i <= N; i++) { a[i] = Math.sin(2 * Math.PI * i * hz / StdAudio.SAMPLE_RATE); } // play it using standard audio StdAudio.play(a); } } }
Transition.java
/************************************************************************* * Compilation: javac Transition.java * Execution: java Transition < input.txt * Data files: http://introcs.cs.princeton.edu/16pagerank/tiny.txt * http://introcs.cs.princeton.edu/16pagerank/medium.txt * * This program is a filter that reads links from standard input and * produces the corresponding transition matrix on standard output. * First, it processes the input to count the outlinks from each page. * Then it applies the 90-10 rule to compute the transition matrix. * It assumes that there are no pages that have no outlinks in the * input (see Exercise 1.6.3). * * % more tiny.txt * 5 * 0 1 * 1 2 1 2 * 1 3 1 3 1 4 * 2 3 * 3 0 * 4 0 4 2 * * % java Transition < tiny.txt * 5 5 * 0.02 0.92 0.02 0.02 0.02 * 0.02 0.02 0.38 0.38 0.20 * 0.02 0.02 0.02 0.92 0.02 * 0.92 0.02 0.02 0.02 0.02 * 0.47 0.02 0.47 0.02 0.02 * *************************************************************************/ public class Transition { public static void main(String[] args) { int N = StdIn.readInt(); // number of pages int[][] counts = new int[N][N]; // counts[i][j] = # links from page i to page j int[] outDegree = new int[N]; // outDegree[j] = # links from page i to anywhere // Accumulate link counts. while (!StdIn.isEmpty()) { int i = StdIn.readInt(); int j = StdIn.readInt(); outDegree[i]++; counts[i][j]++; } StdOut.println(N + " " + N); // Print probability distribution for row i. for (int i = 0; i < N; i++) { // Print probability for column j. for (int j = 0; j < N; j++) { double p = .90*counts[i][j]/outDegree[i] + .10/N; StdOut.printf("%7.5f ", p); } StdOut.println(); } } }
RandomSurfer.java
/************************************************************************* * Compilation: javac RandomSurfer.java * Execution: java RandomSurfer T * Data files: http://introcs.cs.princeton.edu/16pagerank/tiny.txt * http://introcs.cs.princeton.edu/16pagerank/medium.txt * * % java Transition < tiny.txt | java RandomSurfer 1000000 * 0.27297 0.26583 0.14598 0.24729 0.06793 * *************************************************************************/ public class RandomSurfer { public static void main(String[] args) { int T = Integer.parseInt(args[0]); // number of moves int M = StdIn.readInt(); // number of pages - ignore since M = N int N = StdIn.readInt(); // number of pages // Read transition matrix. double[][] p = new double[N][N]; // p[i][j] = prob. that surfer moves from page i to page j for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) p[i][j] = StdIn.readDouble(); int[] freq = new int[N]; // freq[i] = # times surfer hits page i // Start at page 0. int page = 0; for (int t = 0; t < T; t++) { // Make one random move. double r = Math.random(); double sum = 0.0; for (int j = 0; j < N; j++) { // Find interval containing r. sum += p[page][j]; if (r < sum) { page = j; break; } } freq[page]++; } // Print page ranks. for (int i = 0; i < N; i++) { StdOut.printf("%8.5f", (double) freq[i] / T); } StdOut.println(); } }
Markov.java
/************************************************************************* * Compilation: javac Markov.java * Execution: java Markov T * Data files: http://introcs.cs.princeton.edu/16pagerank/tiny.txt * http://introcs.cs.princeton.edu/16pagerank/medium.txt * * This program reads a transition matrix from standard input and * computes the probabilities that a random surfer lands on each page * (page ranks) after T matrix-vector multiplies. * * % java Transition < tiny.txt | java Markov 40 * 0.27303 0.26573 0.14618 0.24723 0.06783 * *************************************************************************/ public class Markov { public static void main(String[] args) { int T = Integer.parseInt(args[0]); // number of iterations int N = StdIn.readInt(); // number of pages StdIn.readInt(); // ignore integer required by input format // Read p[][] from StdIn. double[][] p = new double[N][N]; // p[i][j] = prob. surfer moves from page i to page j for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) p[i][j] = StdIn.readDouble(); // Use the power method to compute page ranks. double[] rank = new double[N]; rank[0] = 1.0; for (int t = 0; t < T; t++) { // Compute effect of next move on page ranks. double[] newRank = new double[N]; for (int j = 0; j < N; j++) { // New rank of page j is dot product of old ranks and column j of p[][]. for (int k = 0; k < N; k++) newRank[j] += rank[k]*p[k][j]; } // Update page ranks. rank = newRank; } // print page ranks for (int i = 0; i < N; i++) { StdOut.printf("%8.5f", rank[i]); } StdOut.println(); } }
PrimeSieve.java
/************************************************************************* * Compilation: javac PrimeSieve.java * Execution: java -Xmx1100m PrimeSieve N * * Computes the number of primes less than or equal to N using * the Sieve of Eratosthenes. * * % java PrimeSieve 25 * The number of primes <= 25 is 9 * * % java PrimeSieve 100 * The number of primes <= 100 is 25 * * % java -Xmx100m PrimeSieve 100000000 * The number of primes <= 100000000 is 5761455 * * % java PrimeSieve -Xmx1100m 1000000000 * The number of primes <= 1000000000 is 50847534 * * * The 110MB and 1100MB is the amount of memory you want to allocate * to the program. If your computer has less, make this number smaller, * but it may prevent you from solving the problem for very large * values of N. * * * N Primes <= N * --------------------------------- * 10 4 * 100 25 * 1,000 168 * 10,000 1,229 * 100,000 9,592 * 1,000,000 78,498 * 10,000,000 664,579 * 100,000,000 5,761,455 * 1,000,000,000 50,847,534 * *************************************************************************/ public class PrimeSieve { public static void main(String[] args) { int N = Integer.parseInt(args[0]); // initially assume all integers are prime boolean[] isPrime = new boolean[N + 1]; for (int i = 2; i <= N; i++) { isPrime[i] = true; } // mark non-primes <= N using Sieve of Eratosthenes for (int i = 2; i*i <= N; i++) { // if i is prime, then mark multiples of i as nonprime // suffices to consider mutiples i, i+1, ..., N/i if (isPrime[i]) { for (int j = i; i*j <= N; j++) { isPrime[i*j] = false; } } } // count primes int primes = 0; for (int i = 2; i <= N; i++) { if (isPrime[i]) primes++; } System.out.println("The number of primes <= " + N + " is " + primes); } }
CouponCollector.java
/************************************************************************* * Compilation: javac CouponCollector.java * Execution: java CouponCollector N * * Given N distinct card types, how many random cards do you need * do collect before you have (at least) one of each type? * This program simulates this random process. * * * % java CouponCollector 1000 * 6583 * * % java CouponCollector 1000 * 6477 * * % java CouponCollector 1000000 * 12782673 * *************************************************************************/ public class CouponCollector { public static void main(String[] args) { int N = Integer.parseInt(args[0]); // number of card types boolean[] found = new boolean[N]; // found[i] = true if card i has been collected int cardcnt = 0; // total number of cards collected int valcnt = 0; // number of distinct cards // repeatedly choose a random card and check whether it's a new one while (valcnt < N) { int val = (int) (Math.random() * N); // random card between 0 and N-1 cardcnt++; // we collected one more card if (!found[val]) valcnt++; // it's a new card type found[val] = true; // update found[] } // print the total number of cards collected System.out.println(cardcnt); } }
Sample.java
/************************************************************************* * Compilation: javac Sample.java * Execution: java Sample M N * * This program takes two command-line arguments M and N and produces * a random sample of M of the integers from 0 to N-1. * * % java Sample 6 49 * 10 20 0 46 40 6 * * % java Sample 10 1000 * 656 488 298 534 811 97 813 156 424 109 * *************************************************************************/ public class Sample { public static void main(String[] args) { int M = Integer.parseInt(args[0]); // choose this many elements int N = Integer.parseInt(args[1]); // from 0, 1, ..., N-1 // create permutation 0, 1, ..., N-1 int[] perm = new int[N]; for (int i = 0; i < N; i++) perm[i] = i; // create random sample in perm[0], perm[1], ..., perm[M-1] for (int i = 0; i < M; i++) { // random integer between i and N-1 int r = i + (int) (Math.random() * (N-i)); // swap elements at indices i and r int t = perm[r]; perm[r] = perm[i]; perm[i] = t; } // print results for (int i = 0; i < M; i++) System.out.print(perm[i] + " "); System.out.println(); } }
Factors.java
/************************************************************************* * Compilation: javac Factors.java * Execution: java Factors N * * Computes the prime factorization of N using brute force. * * % java Factors 81 * The prime factorization of 81 is: 3 3 3 3 * * % java Factors 168 * The prime factorization of 168 is: 2 2 2 3 7 * * % java Factors 4444444444 * The prime factorization of 4444444444 is: 2 2 11 41 271 9091 * * % java Factors 4444444444444463 * The prime factorization of 4444444444444463 is: 4444444444444463 * * % java Factors 10000001400000049 * The prime factorization of 10000001400000049 is: 100000007 100000007 * * % java Factors 1000000014000000049 * The prime factorization of 1000000014000000049 is: 1000000007 1000000007 * * % java Factors 9201111169755555649 * The prime factorization of 9201111169755555649 is: 3033333343 3033333343 * * Can use these for timing tests - biggest 3, 6, 9, 12, 15, and 18 digit primes * % java Factors 997 * % java Factors 999983 * % java Factors 999999937 * % java Factors 999999999989 * % java Factors 999999999999989 * % java Factors 999999999999999989 * * Remarks * ------- * - Tests i*i <= N instead of i <= N for efficiency. * * - The last two examples still take a few minutes. * *************************************************************************/ public class Factors { public static void main(String[] args) { // command-line argument long n = Long.parseLong(args[0]); System.out.print("The prime factorization of " + n + " is: "); // for each potential factor i for (long i = 2; i*i <= n; i++) { // if i is a factor of N, repeatedly divide it out while (n % i == 0) { System.out.print(i + " "); n = n / i; } } // if biggest factor occurs only once, n > 1 if (n > 1) System.out.println(n); else System.out.println(); } }
Gambler.java
/************************************************************************* * Compilation: javac Gambler.java * Execution: java Gambler stake goal N * * Simulates a gambler who start with $stake and place fair $1 bets * until she goes broke or reach $goal. Keeps track of the number of * times she wins and the number of bets she makes. Run the experiment N * times, averages the results, and prints them out. * * % java Gambler 50 250 1000 * Percent of games won = 19.0 * Avg # bets = 9676.302 * * % java Gambler 50 150 1000 * Percent of games won = 31.9 * Avg # bets = 4912.13 * * % java Gambler 50 100 1000 * Percent of games won = 49.6 * Avg # bets = 2652.352 * *************************************************************************/ public class Gambler { public static void main(String[] args) { int stake = Integer.parseInt(args[0]); // gambler's stating bankroll int goal = Integer.parseInt(args[1]); // gambler's desired bankroll int T = Integer.parseInt(args[2]); // number of trials to perform int bets = 0; // total number of bets made int wins = 0; // total number of games won // repeat N times for (int t = 0; t < T; t++) { // do one gambler's ruin simulation int cash = stake; while (cash > 0 && cash < goal) { bets++; if (Math.random() < 0.5) cash++; // win $1 else cash--; // lose $1 } if (cash == goal) wins++; // did gambler go achieve desired goal? } // print results System.out.println(wins + " wins of " + T); System.out.println("Percent of games won = " + 100.0 * wins / T); System.out.println("Avg # bets = " + 1.0 * bets / T); } }
Binary.java
/************************************************************************* * Compilation: javac Binary.java * Execution: java Binary n * * Prints out n in binary. * * % java Binary 5 * 101 * * % java Binary 106 * 1101010 * * % java Binary 0 * 0 * * % java Binary 16 * 10000 * * Limitations * ----------- * Does not handle negative integers. * * Remarks * ------- * could use Integer.toBinaryString(N) instead. * *************************************************************************/ public class Binary { public static void main(String[] args) { // read in the command-line argument int n = Integer.parseInt(args[0]); // set v to the largest power of two that is <= n int v = 1; while (v <= n/2) { v = v * 2; } // check for presence of powers of 2 in n, from largest to smallest while (v > 0) { // v is not present in n if (n < v) { System.out.print(0); } // v is present in n, so remove v from n else { System.out.print(1); n = n - v; } // next smallest power of 2 v = v / 2; } System.out.println(); } }
Sqrt.java
/************************************************************************* * Compilation: javac Sqrt.java * Execution: java Sqrt c * * Computes the square root of a nonnegative number c using * Newton's method: * - initialize t = c * - replace t with the average of c/t and t * - repeat until desired accuracy reached * * % java Sqrt 2 * 1.414213562373095 * * % java Sqrt 1000000 * 1000.0 * * % java Sqrt 0.4 * 0.6324555320336759 * * % java Sqrt 1048575 * 1023.9995117186336 * * % java Sqrt 16664444 * 4082.2106756021303 * * % java Sqrt 0 * 0.0 * * % java Sqrt 1e-50 * 9.999999999999999E-26 * * * Remarks * ---------- * - using Math.abs() is required if c < 1 * * * Known bugs * ---------- * - goes into an infinite loop if the input is negative * *************************************************************************/ public class Sqrt { public static void main(String[] args) { // read in the command-line argument double c = Double.parseDouble(args[0]); double epsilon = 1e-15; // relative error tolerance double t = c; // estimate of the square root of c // repeatedly apply Newton update step until desired precision is achieved while (Math.abs(t - c/t) > epsilon*t) { t = (c/t + t) / 2.0; } // print out the estimate of the square root of c System.out.println(t); } }
Harmonic.java
/************************************************************************* * Compilation: javac Harmonic.java * Execution: java Harmonic N * * Prints the Nth harmonic number: 1/1 + 1/2 + ... + 1/N. * * % java Harmonic 10 * 2.9289682539682538 * * % java Harmonic 10000 * 9.787606036044348 * *************************************************************************/ public class Harmonic { public static void main(String[] args) { // command-line argument int N = Integer.parseInt(args[0]); // compute 1/1 + 1/2 + 1/3 + ... + 1/N double sum = 0.0; for (int i = 1; i <= N; i++) { sum += 1.0 / i; } // print out Nth harmonic number System.out.println(sum); } }
DivisorPattern.java
/************************************************************************* * Compilation: javac DivisorPattern.java * Execution: java DivisorPattern N * * Prints a table where entry (i, j) is a '* ' if i divides j * or j divides i and '. ' otherwise. * * * % java DivisorPattern 20 * * * * * * * * * * * * * * * * * * * * * 1 * * * * * * * * * * * * 2 * * * * * * * * 3 * * * * * * * * 4 * * * * * * 5 * * * * * * * 6 * * * * 7 * * * * * * 8 * * * * * 9 * * * * * * 10 * * * 11 * * * * * * * 12 * * * 13 * * * * * 14 * * * * * 15 * * * * * * 16 * * * 17 * * * * * * * 18 * * * 19 * * * * * * * 20 * *************************************************************************/ public class DivisorPattern { public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { if (i % j == 0 || j % i == 0) { System.out.print("* "); } else { System.out.print(" "); } } System.out.println(i); } } }
Subscribe to:
Posts (Atom)