Extra Java Programs
Extra Java Programs
Contents
Preface 4
Data Files 7
1 Imperative Programming 8
1.1 Your First Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.1.1 HelloWorld.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.1.2 UseArgument.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2 Basic Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2.1 DateFormats.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2.2 SumOfSquares.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2.3 Quadratic.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2.4 LeapYear.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3.1 Grade.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3.2 Flip.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3.3 NHellos.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3.4 PowersOfTwo.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3.5 DivisorPattern.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3.6 Harmonic.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.3.7 Sqrt.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.3.8 Binary.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.3.9 Gambler.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.3.10 Factors.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.4 Collection Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.4.1 Sample.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.4.2 CouponCollector.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.4.3 PrimeSieve.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.4.4 SelfAvoid.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.5 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.5.1 RandomSeq.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.5.2 TwentyQuestions.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.5.3 Average.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.5.4 RangeFilter.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.5.5 PlotFilter.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.5.6 BouncingBall.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.5.7 PlayThatTune.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.6 Case Study: What Makes Google Different? (PageRank Algorithm) . . . . . . . . . . . . . . . . . . . . . . . 22
1.6.1 Transition.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.6.2 RandomSurfer.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.6.3 Markov.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2 Procedural Programming 24
2.1 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.1.1 HarmonicRedux.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.1.2 CouponCollectorRedux.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.1.3 PlayThatTuneDeluxe.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.2 Modules and Clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.2.1 GaussianTable.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.2.2 Gaussian.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.2.3 IFS.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
1 / 78
Introduction to Programming in Java
2.2.4 Matrix.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.3 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3.1 Factorial.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3.2 Euclid.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3.3 TowersOfHanoi.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.3.4 HTree.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.3.5 Fibonacci.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.4 Case Study: Fermi’s Paradox (Percolation Problem) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.4.1 PercolationIO.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.4.2 Percolation.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.4.3 Visualize.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.4.4 Estimate.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.4.5 PercolationPlot.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3 Object-oriented Programming 37
3.1 Using Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.1.1 PotentialGene.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.1.2 AlbersSquares.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.1.3 Luminance.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.1.4 Grayscale.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.1.5 Fade.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.1.6 Cat.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.1.7 Split.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.2 Creating Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.2.1 TimeOps.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.2.2 Stopwatch.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.2.3 Bernoulli.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.2.4 Histogram.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.2.5 Drunks.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.2.6 Turtle.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.3 Designing Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.3.1 Complex.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.3.2 Mandelbrot.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.3.3 Vector.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.3.4 Sketch.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.3.5 CompareDocuments.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.3.6 Counter.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
3.3.7 Country.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.3.8 FibonacciSequence.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.3.9 Words.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.3.10 ErrorHandling.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.4 Case Study: The Music of the Spheres (N -body Problem) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
3.4.1 Body.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
3.4.2 Universe.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.4.3 NBody.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
2 / 78
Introduction to Programming in Java
4.2.5 Merge.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
4.3 Stacks, Queues, and Symbol Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.3.1 Reverse.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.3.2 ArrayStack.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.3.3 KthFromLast.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.3.4 ArrayQueue.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.3.5 FrequencyCounter.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
4.3.6 SymbolTable.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
4.4 Case Study: Six Degrees of Separation (Small-world Problem) . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.4.1 Graph.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.4.2 PathFinder.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
4.4.3 Separation.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3 / 78
Introduction to Programming in Java
Preface
This document contains listings of the programs I use to teach an introductory course on programming in Java. Most of the
programs are from the excellent textbook Computer Science: An Interdisciplinary Approach W by Robert Sedgewick and
Kevin Wayne. The programs have been modified for clarity and consistency. The listing for each program includes colorized
Java code for the program with line numbers, and a terminal session showing the command to run the program along with
the program output.
The programs are available as an IntelliJ project (https://swamiiyer.net/teaching/ipj.zip W). Consult the section Programming
Environment Setup for instructions on how to setup your personal computer with the environment needed to run the
programs. To open the project, launch IntelliJ and open ~/workspace/ipj/programs. You can compile and run a program on
the IntelliJ terminal, as follows:
& ~/workspace/ipj/programs
$ javac -d out src / HelloWorld . java
$ java HelloWorld
Hello , World
$ _
You can compile all the programs at once on the IntelliJ terminal, as follows:
& ~/workspace/ipj/programs
$ ant
$ _
You can also run/debug a program within IntelliJ by selecting an appropriate Run/Debug configuration and clicking Run or
Debug.
Input data files are available under the data folder, also included in ipj.zip. The table in section Data Files lists the names of
the data-driven programs, references to them within this document, and the relevant data files.
4 / 78
Introduction to Programming in Java
In the following sections, lines starting with the $ symbol denote commands to be run in the terminal, and the lines
starting with the # symbol denote comments. When you run the suggested commands, do not copy-paste the commands
into the terminal; type them out instead.
On Ubuntu Linux
1. Launch a terminal and run the following commands.
& ~/
# Change to your home folder .
$ cd $ HOME
# Install OpenJDK and ant .
$ sudo apt - get install openjdk -11 - jdk ant
# Create lib and workspace folders .
$ mkdir lib workspace
# Download stdlib . jar under ~/ lib .
$ wget https :// swamiiyer . net / teaching / stdlib . jar -P lib
# Set the CLASSPATH environment variable .
$ echo " export CLASSPATH =.:./ out : $ HOME / lib / stdlib . jar " >> $ HOME /. bashrc
# Download ipj . zip .
$ wget https :// www . swamiiyer . net / teaching / ipj . zip
# Unzip ipj . zip under ~/ workspace .
$ unzip ipj . zip -d workspace
# Remove ipj . zip .
$ rm ipj . zip
On Mac OS X
1. Launch a terminal and run the following commands.
& ~/
# Change to your home folder .
$ cd $ HOME
# Install brew .
$ / usr / bin / ruby -e " $ ( curl - fsSL https :// raw . g i t h u b u s e r c o n t e n t . com / Homebrew / install / master / install )"
# Install OpenJDK .
$ brew install openjdk@11
# Install ant .
$ brew install ant
# Create lib and workspace folders .
$ mkdir lib workspace
# Download stdlib . jar under ~/ lib .
$ wget http :// swamiiyer . net / teaching / stdlib . jar -P lib
# Set the CLASSPATH environment variable .
$ echo " export CLASSPATH =.:./ out : $ HOME / lib / stdlib . jar " >> $ HOME /. bash_profile
# Download ipj . zip .
$ wget https :// www . swamiiyer . net / teaching / ipj . zip
# Unzip ipj . zip under ~/ workspace .
$ unzip ipj . zip -d workspace
# Remove ipj . zip .
$ rm ipj . zip
# Change your shell to bash .
$ chsh -s / bin / bash
2. Download and install IntelliJ (Community Edition) W. Launch IntelliJ, go to Configure → Settings → Tools → Terminal
and set Shell path to /bin/bash.
On Windows
1. Launch a powershell terminal and run the following commands.
5 / 78
Introduction to Programming in Java
& ~/
# Change to your home folder .
$ cd $ HOME
# Create lib and workspace folders .
$ mkdir lib , workspace
# Download stdlib . jar under ~/ lib .
$ wget -O lib \ stdlib . jar https :// www . swamiiyer . net / teaching / stdlib . jar
# Set the CLASSPATH environment variable .
$ setx CLASSPATH ".;.\ out ; $ HOME \ lib \ stdlib . jar "
# Download ipj . zip .
$ wget -O ipj . zip https :// www . swamiiyer . net / teaching / ipj . zip
# Unzip ipj . zip under ~/ workspace .
$ Expand - Archive - LiteralPath ipj . zip - De s ti na t io nP at h workspace
# Remove ipj . zip .
$ rm ipj . zip
2. Download and unzip OpenJDK 11 W for Windows under some folder. Run the following command, replacing the XYZ
with the path to the folder within that contains the bin folder.
& ~/
# Update the PATH environment variable .
$ setx PATH " $ env : PATH ; XYZ \ bin "
3. Download and unzip Ant W under some folder. Run the following command, replacing XYZ with the path to the folder.
& ~/
# Update the PATH environment variable .
$ setx PATH " $ env : PATH ; XYZ \ bin "
4. Download and install IntelliJ (Community Edition) W. Launch IntelliJ, go to Configure → Settings → Tools → Terminal
and set Shell path to powershell.
6 / 78
Introduction to Programming in Java
Data Files
Program Reference Data Files
PlotFilter.java 1.5.5 usa.txt
PlayThatTune.java 1.5.7 ascale.txt, elise.txt, entertainer.txt, firstcut.txt, freebird.txt, looney.txt, stairwaytoheaven.txt
Transition.java 1.6.1 small.txt, medium.txt
PlayThatTuneDeluxe.java 2.1.3 ascale.txt, elise.txt, entertainer.txt, firstcut.txt, freebird.txt, looney.txt, stairwaytoheaven.txt
IFS.java 2.2.3 barnsley.txt, coral.txt, culcita.txt, cyclosorus.txt, dragon.txt, fishbone.txt, floor.txt, koch.txt,
sierpinski.txt, spiral.txt, swirl.txt, tree.txt, zigzag.txt
Percolation.java 2.4.2 test5.txt, test8.txt
Grayscale.java 3.1.4 darwin.jpg, darwin.png, mandrill.png, mandrill.png
Fade.java 3.1.5 darwin.jpg, darwin.png, mandrill.png, mandrill.png
Cat.java 3.1.6 in1.txt, in2.txt
Split.java 3.1.7 amino.csv, djia.csv, elements.csv, ip-by-country.csv, ip.csv, morse.csv, phone-na.csv
Sketch.java 3.3.4 actg.txt, constitution.txt, djia.csv, huckfinn.txt, prejudice.txt, tale.txt, tomsawyer.txt
CompareDocuments.java 3.3.5 documents.txt, actg.txt, constitution.txt, djia.csv, huckfinn.txt, prejudice.txt, tale.txt,
tomsawyer.txt
NBody.java 3.4.3 2bodytiny.txt, 2body.txt, 3body.txt, 4body.txt
ThreeSum.java 4.1.1 1Kints.txt, 2Kints.txt, 4Kints.txt, 8Kints.txt, 16Kints.txt, 32Kints.txt
LinearSearch.java 4.2.1 tinyW.txt, tinyT.txt, largeW.txt, largeT.txt
BinarySearch.java 4.2.2 tinyW.txt, tinyT.txt, largeW.txt, largeT.txt
Zipf.java 4.2.3 constitution.txt, huckfinn.txt, mobydick.txt, prejudice.txt, tale.txt, tomsawyer.txt
Insertion.java 4.2.4 constitution.txt, huckfinn.txt, mobydick.txt, prejudice.txt, tale.txt, tomsawyer.txt
Merge.java 4.2.5 constitution.txt, huckfinn.txt, mobydick.txt, prejudice.txt, tale.txt, tomsawyer.txt
ArrayStack.java 4.3.2 tobe.txt
ArrayQueue.java 4.3.4 tobe.txt
FrequencyCounter.java 4.3.5 mobydick.txt, constitution.txt, huckfinn.txt, prejudice.txt, tale.txt, tomsawyer.txt
Graph.java 4.4.1 tinygraph.txt, routes.txt
PathFinder.java 4.4.2 tinygraph.txt, routes.txt
Separation.java 4.4.3 tinymovies.txt, movies.txt
7 / 78
Introduction to Programming in Java
1 Imperative Programming
1.1 Your First Programs
1.1.1 HelloWorld.java
L HelloWorld.java
1 // Writes the message " Hello , World " to standard output .
2
3 import stdlib . StdOut ;
4
5 public class HelloWorld {
6 // Entry point .
7 public static void main ( String [] args ) {
8 StdOut . println ( " Hello , World " );
9 }
10 }
& ~/workspace/ipj/programs
$ java HelloWorld
Hello , World
$ _
1.1.2 UseArgument.java
L UseArgument.java
1 // Accepts a name as command - line argument ; and writes a message containing that name to standard
2 // output .
3
4 import stdlib . StdOut ;
5
6 public class UseArgument {
7 // Entry point .
8 public static void main ( String [] args ) {
9 StdOut . print ( " Hi , " );
10 StdOut . print ( args [0]);
11 StdOut . println ( " . How are you ? " );
12 }
13 }
& ~/workspace/ipj/programs
$ java UseArgument Alice
Hi , Alice . How are you ?
$ java UseArgument Bob
Hi , Bob . How are you ?
$ java UseArgument Carol
Hi , Carol . How are you ?
$ _
8 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java DateFormats 14 03 1879
14/03/1879
03/14/1879
1879/03/14
$ _
1.2.2 SumOfSquares.java
L SumOfSquares.java
1 // Accepts x ( int ) and y ( int ) as command - line arguments ; and writes the sum of their squares to
2 // standard output .
3
4 import stdlib . StdOut ;
5
6 public class SumOfSquares {
7 // Entry point .
8 public static void main ( String [] args ) {
9 int x = Integer . parseInt ( args [0]);
10 int y = Integer . parseInt ( args [1]);
11 int result = x * x + y * y ;
12 StdOut . println ( result );
13 }
14 }
& ~/workspace/ipj/programs
$ java SumOfSquares 3 4
25
$ java SumOfSquares 6 8
100
$ _
1.2.3 Quadratic.java
L Quadratic.java
1 // Accepts a ( double ) , b ( double ) , and c ( double ) as command - line arguments ; and writes the two
2 // roots of the quadratic equation ax ^2 + bx + c = 0 to standard output .
3
4 import stdlib . StdOut ;
5
6 public class Quadratic {
7 // Entry point .
8 public static void main ( String [] args ) {
9 double a = Double . parseDouble ( args [0]);
10 double b = Double . parseDouble ( args [1]);
11 double c = Double . parseDouble ( args [2]);
12 double discriminant = b * b - 4 * a * c ;
13 double root1 = ( - b + Math . sqrt ( discriminant )) / (2 * a );
14 double root2 = ( - b - Math . sqrt ( discriminant )) / (2 * a );
15 StdOut . println ( " Root # 1 = " + root1 );
16 StdOut . println ( " Root # 2 = " + root2 );
17 }
18 }
& ~/workspace/ipj/programs
$ java Quadratic 1 -5 6
Root # 1 = 3.0
Root # 2 = 2.0
$ java Quadratic 1 -1 -1
Root # 1 = 1. 6 18 0 33 9 8 8 7 4 9 8 9 5
Root # 2 = -0.6180339887498949
$ java Quadratic 1 1 1
Root # 1 = NaN
Root # 2 = NaN
9 / 78
Introduction to Programming in Java
$ _
1.2.4 LeapYear.java
L LeapYear.java
1 // Accepts y ( int ) as command - line argument representing a year ; and writes to standard output
2 // whether the year is a leap year or not .
3
4 import stdlib . StdOut ;
5
6 public class LeapYear {
7 // Entry point .
8 public static void main ( String [] args ) {
9 int y = Integer . parseInt ( args [0]);
10 boolean result = y % 4 == 0 && y % 100 != 0 || y % 400 == 0;
11 StdOut . println ( result );
12 }
13 }
& ~/workspace/ipj/programs
$ java LeapYear 2020
True
$ java LeapYear 1900
False
$ java LeapYear 2000
True
$ _
10 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Grade 97
A
$ java Grade 56
F
$ _
1.3.2 Flip.java
L Flip.java
1 // Simulates a coin flip by writing " Heads " or " Tails " to standard output .
2
3 import stdlib . StdOut ;
4 import stdlib . StdRandom ;
5
6 public class Flip {
7 // Entry point .
8 public static void main ( String [] args ) {
9 String result = StdRandom . bernoulli () ? " Heads " : " Tails " ;
10 StdOut . println ( result );
11 }
12 }
& ~/workspace/ipj/programs
$ java Flip
Heads
$ java Flip
Heads
$ java Flip
Tails
$ _
1.3.3 NHellos.java
L NHellos.java
1 // Accepts n ( int ) as command - line argument ; and writes n Hellos to standard output .
2
3 import stdlib . StdOut ;
4
5 public class NHellos {
6 // Entry point .
7 public static void main ( String [] args ) {
8 int n = Integer . parseInt ( args [0]);
9 int i = 1;
10 while ( i <= n ) {
11 StdOut . println ( " Hello # " + i );
12 i ++;
13 }
14 }
15 }
& ~/workspace/ipj/programs
$ java NHellos 10
Hello # 1
Hello # 2
Hello # 3
Hello # 4
Hello # 5
Hello # 6
Hello # 7
Hello # 8
Hello # 9
Hello # 10
$ _
11 / 78
Introduction to Programming in Java
1.3.4 PowersOfTwo.java
L PowersOfTwo.java
1 // Accepts n ( int ) as command - line argument ; and writes to standard output a table of powers of 2
2 // that are less than or equal to 2^ n .
3
4 import stdlib . StdOut ;
5
6 public class PowersOfTwo {
7 // Entry point .
8 public static void main ( String [] args ) {
9 int n = Integer . parseInt ( args [0]);
10 int power = 1;
11 for ( int i = 0; i <= n ; i ++) {
12 StdOut . println ( i + " " + power );
13 power *= 2;
14 }
15 }
16 }
& ~/workspace/ipj/programs
$ java PowersOfTwo 8
0 1
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
$ _
1.3.5 DivisorPattern.java
L DivisorPattern.java
1 // Accepts n ( int ) as command - line argument ; and writes to standard output a table where entry
2 // (i , j ) is a "* " if j divides i or i divides j and a " " otherwise .
3
4 import stdlib . StdOut ;
5
6 public class DivisorPatt ern {
7 // Entry point .
8 public static void main ( String [] args ) {
9 int n = Integer . parseInt ( args [0]);
10 for ( int i = 1; i <= n ; i ++) {
11 for ( int j = 1; j <= n ; j ++) {
12 if ( i % j == 0 || j % i == 0) {
13 StdOut . print ( " * " );
14 } else {
15 StdOut . print ( " " );
16 }
17 }
18 StdOut . println ( i );
19 }
20 }
21 }
& ~/workspace/ipj/programs
$ java DivisorPattern 20
* * * * * * * * * * * * * * * * * * * * 1
* * * * * * * * * * * 2
* * * * * * * 3
* * * * * * * 4
* * * * * 5
* * * * * * 6
* * * 7
* * * * * 8
* * * * 9
* * * * * 10
* * 11
* * * * * * 12
* * 13
12 / 78
Introduction to Programming in Java
* * * * 14
* * * * 15
* * * * * 16
* * 17
* * * * * * 18
* * 19
* * * * * * 20
$ _
1.3.6 Harmonic.java
L Harmonic.java
1 // Accepts n ( int ) as command - line argument ; and writes the nth harmonic number (1 + 1/2 + ... +
2 // 1/ n ) to standard output .
3
4 import stdlib . StdOut ;
5
6 public class Harmonic {
7 // Entry point .
8 public static void main ( String [] args ) {
9 int n = Integer . parseInt ( args [0]);
10 double total = 0.0;
11 for ( int i = 1; i <= n ; i ++) {
12 total += 1.0 / i ;
13 }
14 StdOut . println ( total );
15 }
16 }
& ~/workspace/ipj/programs
$ java Harmonic 10
2 . 9 2 8 9 6 8 2 53 9 6 8 25 3 8
$ java Harmonic 1000
7 . 4 8 5 470 8 60 5 50 3 43
$ java Harmonic 10000
9 . 7 8 7 606 0 36 0 44 3 48
$ _
1.3.7 Sqrt.java
L Sqrt.java
1 // Accepts c ( double ) as command - line argument ; and writes the square root of c to standard output ,
2 // computed using Newton ’s method .
3
4 import stdlib . StdOut ;
5
6 public class Sqrt {
7 // Entry point .
8 public static void main ( String [] args ) {
9 double c = Double . parseDouble ( args [0]);
10 double EPSILON = 1e -15;
11 double t = c ;
12 while ( Math . abs (1 - c / ( t * t )) > EPSILON ) {
13 t = ( c / t + t ) / 2;
14 }
15 StdOut . println ( t );
16 }
17 }
& ~/workspace/ipj/programs
$ java Sqrt 2
1 . 4 1 4 21 3 56 2 37 30 9 5
$ java Sqrt 1000000
1000.0
$ java Sqrt 0.4
0 . 6 3 2 4 5 5 5 32 0 3 3 67 5 9
$ java Sqrt 1048575
1 0 2 3 . 9 99 5 1 1 7 18 6 3 3 6
$ java Sqrt 16664444
4 0 8 2 . 2 10 6 7 5 6 02 1 3 0 3
$ java Sqrt 1e -50
13 / 78
Introduction to Programming in Java
9 . 9 9 9 99 9 99 9 99 99 9 9 E -26
$ _
1.3.8 Binary.java
L Binary.java
1 // Accepts n ( int ) as command - line argument ; and writes the binary represe ntation of n to
2 // standard output .
3
4 import stdlib . StdOut ;
5
6 public class Binary {
7 // Entry point .
8 public static void main ( String [] args ) {
9 int n = Integer . parseInt ( args [0]);
10 int v = 1;
11 while ( v <= n / 2) {
12 v *= 2;
13 }
14 while ( v > 0) {
15 if ( n < v ) {
16 StdOut . print ( " 0 " );
17 } else {
18 StdOut . print ( " 1 " );
19 n -= v ;
20 }
21 v /= 2;
22 }
23 StdOut . println ();
24 }
25 }
& ~/workspace/ipj/programs
$ java Binary 19
10011
$ java Binary 255
11111111
$ java Binary 512
1000000000
$ java Binary 1000000000
111011100110101100101000000000
$ _
1.3.9 Gambler.java
L Gambler.java
1 // Accepts stake ( int ) , goal ( int ) , and trials ( int ) as command - line arguments ; runs trials
2 // experiments ( dollar bets ) that start with stake dollars and terminate on 0 dollars or goal ; and
3 // writes the percentage of wins and the average number of bets per experiment to standard output .
4
5 import stdlib . StdOut ;
6 import stdlib . StdRandom ;
7
8 public class Gambler {
9 // Entry point .
10 public static void main ( String [] args ) {
11 int stake = Integer . parseInt ( args [0]);
12 int goal = Integer . parseInt ( args [1]);
13 int trials = Integer . parseInt ( args [2]);
14 int bets = 0;
15 int wins = 0;
16 for ( int t = 0; t < trials ; t ++) {
17 int cash = stake ;
18 while ( cash > 0 && cash < goal ) {
19 bets ++;
20 if ( StdRandom . bernoulli ()) {
21 cash ++;
22 } else {
23 cash - -;
24 }
25 }
26 if ( cash == goal ) {
14 / 78
Introduction to Programming in Java
27 wins ++;
28 }
29 }
30 StdOut . println (100 * wins / trials + " % wins " );
31 StdOut . println ( " Avg # bets : " + bets / trials );
32 }
33 }
& ~/workspace/ipj/programs
$ java Gambler 10 20 1000
50% wins
Avg # bets : 95
$ java Gambler 50 250 100
25% wins
Avg # bets : 12355
$ java Gambler 500 2500 100
18% wins
Avg # bets : 926705
$ _
1.3.10 Factors.java
L Factors.java
1 // Accepts n ( long ) as command - line argument ; and writes the prime factors of n to standard output .
2
3 import stdlib . StdOut ;
4
5 public class Factors {
6 // Entry point .
7 public static void main ( String [] args ) {
8 long n = Long . parseLong ( args [0]);
9 long factor = 2;
10 while ( factor * factor <= n ) {
11 while ( n % factor == 0) {
12 StdOut . print ( factor + " " );
13 n /= factor ;
14 }
15 factor ++;
16 }
17 if ( n > 1) {
18 StdOut . print ( n );
19 }
20 StdOut . println ();
21 }
22 }
& ~/workspace/ipj/programs
$ java Factors 3757208
2 2 2 7 13 13 397
$ java Factors 2 87 99 4 83 72 22 3 11
17 1739347 9739789
$ _
15 / 78
Introduction to Programming in Java
14 perm [ i ] = i ;
15 }
16 for ( int i = 0; i < m ; i ++) {
17 int r = StdRandom . uniform (i , n );
18 int temp = perm [ r ];
19 perm [ r ] = perm [ i ];
20 perm [ i ] = temp ;
21 }
22 for ( int i = 0; i < m ; i ++) {
23 StdOut . print ( perm [ i ] + " " );
24 }
25 StdOut . println ();
26 }
27 }
& ~/workspace/ipj/programs
$ java Sample 6 16
3 5 0 4 6 14
$ java Sample 10 1000
592 276 835 858 306 139 642 507 366 571
$ java Sample 20 20
2 15 19 1 18 16 11 12 9 7 13 5 10 3 4 6 14 17 0 8
$ _
1.4.2 CouponCollector.java
L CouponCollector.java
1 // Accepts n ( int ) as a command - line argument ; and writes to standard output the number of coupons
2 // you collect before obtaining one of each of n types .
3
4 import stdlib . StdOut ;
5 import stdlib . StdRandom ;
6
7 public class CouponC ol le c to r {
8 // Entry point .
9 public static void main ( String [] args ) {
10 int n = Integer . parseInt ( args [0]);
11 int count = 0;
12 int collectedCou nt = 0;
13 boolean [] isCollected = new boolean [ n ];
14 while ( collect edCount < n ) {
15 int value = StdRandom . uniform (0 , n );
16 count ++;
17 if (! isCollected [ value ]) {
18 colle ctedCou nt ++;
19 isCollected [ value ] = true ;
20 }
21 }
22 StdOut . println ( count );
23 }
24 }
& ~/workspace/ipj/programs
$ java CouponCo ll ec tor 1000
7475
$ java CouponCo ll ec tor 1000
6429
$ java C ou po nC ollect or 1000000
14649867
$ _
1.4.3 PrimeSieve.java
L PrimeSieve.java
1 // Accepts n ( int ) as command - line argument ; and writes the number of primes <= n to standard
2 // output .
3
4 import stdlib . StdOut ;
5
6 public class PrimeSieve {
7 // Entry point .
16 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java PrimeSieve 100
25
$ java PrimeSieve 1000
168
$ java PrimeSieve 1000000
78498
$ java PrimeSieve 100000000
5761455
$ _
1.4.4 SelfAvoid.java
L SelfAvoid.java
1 // Accepts n ( int ) and trials ( int ) as command - line arguments ; and writes to standard output the
2 // percentage of dead ends encountered out of trials self - avoiding random walks on an n - by - n
3 // lattice .
4
5 import stdlib . StdOut ;
6 import stdlib . StdRandom ;
7
8 public class SelfAvoid {
9 // Entry point .
10 public static void main ( String [] args ) {
11 int n = Integer . parseInt ( args [0]);
12 int trials = Integer . parseInt ( args [1]);
13 int deadEnds = 0;
14 for ( int t = 0; t < trials ; t ++) {
15 boolean [][] a = new boolean [ n ][ n ];
16 int x = n / 2;
17 int y = n / 2;
18 while ( x > 0 && x < n - 1 && y > 0 && y < n - 1) {
19 a [ x ][ y ] = true ;
20 if ( a [ x - 1][ y ] && a [ x + 1][ y ] && a [ x ][ y - 1] && a [ x ][ y + 1]) {
21 deadEnds ++;
22 break ;
23 }
24 int r = StdRandom . uniform (1 , 5);
25 if ( r == 1 && ! a [ x + 1][ y ]) {
26 x ++;
27 } else if ( r == 2 && ! a [ x - 1][ y ]) {
28 x - -;
29 } else if ( r == 3 && ! a [ x ][ y + 1]) {
30 y ++;
31 } else if ( r == 4 && ! a [ x ][ y - 1]) {
32 y - -;
33 }
34 }
35 }
36 StdOut . println (100 * deadEnds / trials + " % dead ends " );
37 }
38 }
17 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java SelfAvoid 5 1000
0% dead ends
$ java SelfAvoid 20 1000
35% dead ends
$ java SelfAvoid 40 1000
76% dead ends
$ java SelfAvoid 80 1000
97% dead ends
$ _
& ~/workspace/ipj/programs
$ java RandomSeq 10 100 200
149.72
172.12
136.40
169.56
178.92
103.71
126.36
158.63
164.44
136.24
$ _
1.5.2 TwentyQuestions.java
L TwentyQuestions.java
1 // Generates a random integer ; repeatedly accepts user guesses from standard input ; writes " Too
2 // low " or " Too high " to standard output , as appropriate , in response to each guess ; and writes
3 // " You win !" to standard output and exits when the user ’s guess is correct .
4
5 import stdlib . StdIn ;
6 import stdlib . StdOut ;
7 import stdlib . StdRandom ;
8
9 public class TwentyQ ue st i on s {
10 // Entry point .
11 public static void main ( String [] args ) {
12 int RANGE = 1000000;
13 int secret = StdRandom . uniform (1 , RANGE + 1);
14 StdOut . printf ( " I am thinking of a secret number between 1 and % d \ n " , RANGE );
15 int guess = 0;
16 while ( guess != secret ) {
17 StdOut . print ( " What is your guess ? " );
18 guess = StdIn . readInt ();
19 if ( guess < secret ) {
18 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java TwentyQu es ti ons
I am thinking of a secret number between 1 and 1000000
What is your guess ? 500000
Too low
What is your guess ? 750000
Too high
What is your guess ? 625000
Too high
What is your guess ? 562500
Too high
What is your guess ? 531250
Too high
What is your guess ? 515625
Too high
What is your guess ? 507812
Too high
What is your guess ? 503906
Too high
What is your guess ? 501953
Too high
What is your guess ? 500977
Too low
What is your guess ? 501465
Too low
What is your guess ? 501709
Too high
What is your guess ? 501587
Too low
What is your guess ? 501648
Too low
What is your guess ? 501679
Too low
What is your guess ? 501694
Too high
What is your guess ? 501686
You win !
$ _
1.5.3 Average.java
L Average.java
1 // Accepts doubles from standard input ; and writes their average to standard output .
2
3 import stdlib . StdIn ;
4 import stdlib . StdOut ;
5
6 public class Average {
7 // Entry point .
8 public static void main ( String [] args ) {
9 double total = 0.0;
10 int count = 0;
11 while (! StdIn . isEmpty ()) {
12 double x = StdIn . readDouble ();
13 total += x ;
14 count ++;
15 }
16 double average = total / count ;
17 StdOut . println ( " Average is " + average );
18 }
19 }
19 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Average
10.0 5.0 6.0 3.0 7.0 32.0
< ctrl -d >
Average is 10.5
$
1.5.4 RangeFilter.java
L RangeFilter.java
1 // Accepts lo ( int ) and hi ( int ) as command - line arguments and integers from standard input ; and
2 // writes to standard output those integers that are in the range [ lo , hi ].
3
4 import stdlib . StdIn ;
5 import stdlib . StdOut ;
6
7 public class RangeFilter {
8 // Entry point .
9 public static void main ( String [] args ) {
10 int lo = Integer . parseInt ( args [0]);
11 int hi = Integer . parseInt ( args [1]);
12 while (! StdIn . isEmpty ()) {
13 int x = StdIn . readInt ();
14 if ( x >= lo && x <= hi ) {
15 StdOut . print ( x + " " );
16 }
17 }
18 StdOut . println ();
19 }
20 }
& ~/workspace/ipj/programs
$ java RangeFilter 100 400
358 1330 55 165 689 1014 3066 387 575 843 203 48 292 877 65 998
< enter >
358 165 387 203 292
< ctrl -d >
$ _
1.5.5 PlotFilter.java
L PlotFilter.java
1 // Accepts x and y scales and (x , y ) points from standard input ; configures standard draw
2 // appropriately ; and plots the points using standard draw .
3
4 import stdlib . StdDraw ;
5 import stdlib . StdIn ;
6
7 public class PlotFilter {
8 // Entry point .
9 public static void main ( String [] args ) {
10 double x0 = StdIn . readDouble ();
11 double y0 = StdIn . readDouble ();
12 double x1 = StdIn . readDouble ();
13 double y1 = StdIn . readDouble ();
14 StdDraw . setXscale ( x0 , x1 );
15 StdDraw . setYscale ( y0 , y1 );
16 StdDraw . setPenRadius (0.0);
17 StdDraw . e n a b l e D o u b l e B u f f e r i n g ();
18 while (! StdIn . isEmpty ()) {
19 double x = StdIn . readDouble ();
20 double y = StdIn . readDouble ();
21 StdDraw . point (x , y );
22 }
23 StdDraw . show ();
24 }
25 }
& ~/workspace/ipj/programs
$ java PlotFilter < ../ data / usa . txt
$ _
20 / 78
Introduction to Programming in Java
1.5.6 BouncingBall.java
L BouncingBall.java
1 // Draws a bouncing ball using standard draw .
2
3 import stdlib . StdDraw ;
4
5 public class BouncingBall {
6 // Entry point .
7 public static void main ( String [] args ) {
8 double RADIUS = 0.05;
9 double DT = 1.0;
10 int PAUSE = 20;
11 StdDraw . setXscale ( -1.0 , 1.0);
12 StdDraw . setYscale ( -1.0 , 1.0);
13 StdDraw . e n a b l e D o u b l e B u f f e r i n g ();
14 double rx = 0.480;
15 double ry = 0.860;
16 double vx = 0.015;
17 double vy = 0.023;
18 // noinspection I n f i n i t e L o o p S t a t e m e n t
19 while ( true ) {
20 if ( Math . abs ( rx + vx * DT ) + RADIUS > 1.0) {
21 vx = - vx ;
22 }
23 if ( Math . abs ( ry + vy * DT ) + RADIUS > 1.0) {
24 vy = - vy ;
25 }
26 rx += vx * DT ;
27 ry += vy * DT ;
28 StdDraw . clear ( StdDraw . WHITE );
29 StdDraw . filledCircle ( rx , ry , RADIUS );
30 StdDraw . show ();
31 StdDraw . pause ( PAUSE );
32 }
33 }
34 }
& ~/workspace/ipj/programs
$ java BouncingBall
$ _
21 / 78
Introduction to Programming in Java
1.5.7 PlayThatTune.java
L PlayThatTune.java
1 // Accepts sound samples , each characterized by a pitch and a duration , from standard input ; and
2 // plays the sound using standard audio .
3
4 import stdlib . StdAudio ;
5 import stdlib . StdIn ;
6
7 public class PlayThatTune {
8 // Entry point .
9 public static void main ( String [] args ) {
10 int SPS = 44100;
11 int NOTES_ON_SCA LE = 12;
12 double CONCERT_A = 440.0;
13 while (! StdIn . isEmpty ()) {
14 int pitch = StdIn . readInt ();
15 double duration = StdIn . readDouble ();
16 double hz = CONCERT_A * Math . pow (2 , 1.0 * pitch / NOTES _ON_SCAL E );
17 int n = ( int ) ( SPS * duration );
18 double [] note = new double [ n + 1];
19 for ( int i = 0; i <= n ; i ++) {
20 note [ i ] = Math . sin (2 * Math . PI * i * hz / SPS );
21 }
22 StdAudio . play ( note );
23 }
24 }
25 }
& ~/workspace/ipj/programs
$ java PlayThatTune < ../ data / elise . txt
$ _
22 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Transition < ../ data / small . txt
5 5
0.02000 0.92000 0.02000 0.02000 0.02000
0.02000 0.02000 0.38000 0.38000 0.20000
0.02000 0.02000 0.02000 0.92000 0.02000
0.92000 0.02000 0.02000 0.02000 0.02000
0.47000 0.02000 0.47000 0.02000 0.02000
$ _
1.6.2 RandomSurfer.java
L RandomSurfer.java
1 // Accepts moves ( int ) as command - line argument and a transition matrix from standard input ;
2 // performs moves transitions as prescribed by the transition matrix ; and writes the relative
3 // frequency of hitting each page to standard output .
4
5 import stdlib . StdArrayIO ;
6 import stdlib . StdOut ;
7 import stdlib . StdRandom ;
8
9 public class RandomSurfer {
10 // Entry point .
11 public static void main ( String [] args ) {
12 int moves = Integer . parseInt ( args [0]);
13 double [][] t r a n s i t i o n M a t r i x = StdArrayIO . readDouble2D ();
14 int n = t ra n s i t i o n M a t r i x . length ;
15 int [] hits = new int [ n ];
16 int page = 0;
17 for ( int m = 0; m < moves ; m ++) {
18 page = StdRandom . discrete ( t r a n s i t i o n M a t r i x [ page ]);
19 hits [ page ]++;
20 }
21 for ( int hit : hits ) {
22 StdOut . printf ( " %8.5 f " , 1.0 * hit / moves );
23 }
24 StdOut . println ();
25 }
26 }
& ~/workspace/ipj/programs
$ java Transition < ../ data / small . txt | java RandomSurfer 100
0.27000 0.29000 0.10000 0.25000 0.09000
$ java Transition < ../ data / small . txt | java RandomSurfer 10000
0.27170 0.26250 0.14760 0.24650 0.07170
$ java Transition < ../ data / small . txt | java RandomSurfer 10000000
0.27302 0.26573 0.14626 0.24715 0.06785
$ _
23 / 78
Introduction to Programming in Java
1.6.3 Markov.java
L Markov.java
1 // Accepts moves ( int ) as command - line argument and a transition matrix from standard input ;
2 // computes the probabilities that a random surfer lands on each page ( page ranks ) after moves
3 // matrix - vector mu lt ip li c at io n s ; and writes the page ranks to standard output .
4
5 import stdlib . StdArrayIO ;
6 import stdlib . StdOut ;
7
8 public class Markov {
9 // Entry point .
10 public static void main ( String [] args ) {
11 int moves = Integer . parseInt ( args [0]);
12 double [][] t r a n s i t i o n M a t r i x = StdArrayIO . readDouble2D ();
13 int n = t ra n s i t i o n M a t r i x . length ;
14 double [] ranks = new double [ n ];
15 ranks [0] = 1.0;
16 for ( int m = 0; m < moves ; m ++) {
17 double [] newRanks = new double [ n ];
18 for ( int j = 0; j < n ; j ++) {
19 for ( int i = 0; i < n ; i ++) {
20 newRanks [ j ] += ranks [ i ] * t r a n s i t i on M a t r i x [ i ][ j ];
21 }
22 }
23 ranks = newRanks ;
24 }
25 for ( double rank : ranks ) {
26 StdOut . printf ( " %8.5 f " , rank );
27 }
28 StdOut . println ();
29 }
30 }
& ~/workspace/ipj/programs
$ java Transition < ../ data / small . txt | java Markov 20
0.27245 0.26515 0.14669 0.24764 0.06806
$ java Transition < ../ data / small . txt | java Markov 40
0.27303 0.26573 0.14618 0.24723 0.06783
$ _
2 Procedural Programming
2.1 Defining Functions
2.1.1 HarmonicRedux.java
L HarmonicRedux.java
1 // Accepts n ( int ) as command - line argument ; and writes the nth harmonic number (1 + 1/2 + ... +
2 // 1/ n ) to standard output .
3
4 import stdlib . StdOut ;
5
6 public class HarmonicRedux {
7 // Entry point .
8 public static void main ( String [] args ) {
9 int n = Integer . parseInt ( args [0]);
10 StdOut . println ( harmonic ( n ));
11 }
12
13 // Returns the nth harmonic number .
14 private static double harmonic ( int n ) {
15 double total = 0.0;
16 for ( int i = 1; i <= n ; i ++) {
17 total += 1.0 / i ;
18 }
19 return total ;
20 }
21 }
24 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java HarmonicRedux 10
2 . 9 2 8 9 6 8 2 53 9 6 8 25 3 8
$ java HarmonicRedux 1000
7 . 4 8 5 470 8 60 5 50 3 43
$ java HarmonicRedux 10000
9 . 7 8 7 606 0 36 0 44 3 48
$ _
2.1.2 CouponCollectorRedux.java
L CouponCollectorRedux.java
1 // Accepts n ( int ) as a command - line argument ; and writes to standard output the number of coupons
2 // you collect before obtaining one of each of n types .
3
4 import stdlib . StdOut ;
5 import stdlib . StdRandom ;
6
7 public class C o u p o n C o l l e c t o r R e d u x {
8 // Entry point .
9 public static void main ( String [] args ) {
10 int n = Integer . parseInt ( args [0]);
11 StdOut . println ( collect ( n ));
12 }
13
14 // Collects coupons until getting one of each value in the range 0 to n - 1 , and returns the
15 // number of coupons collected .
16 private static int collect ( int n ) {
17 int count = 0;
18 int collectedCou nt = 0;
19 boolean [] isCollected = new boolean [ n ];
20 while ( collect edCount < n ) {
21 int value = getCoupon ( n );
22 count ++;
23 if (! isCollected [ value ]) {
24 colle ctedCou nt ++;
25 isCollected [ value ] = true ;
26 }
27 }
28 return count ;
29 }
30
31 // Returns a random coupon between 0 and n - 1.
32 private static int getCoupon ( int n ) {
33 return StdRandom . uniform (0 , n );
34 }
35 }
& ~/workspace/ipj/programs
$ java C o u p o n C o l l e c t o r R e d u x 1000
7475
$ java C o u p o n C o l l e c t o r R e d u x 1000
6429
$ java C o u p o n C o l l e c t o r R e d u x 1000000
14649867
$ _
2.1.3 PlayThatTuneDeluxe.java
L PlayThatTuneDeluxe.java
1 // Reads sound samples , each characterized by a pitch and a duration , from standard input ; and plays
2 // the sound using standard audio .
3
4 import stdlib . StdAudio ;
5 import stdlib . StdIn ;
6
7 public class P l a yT h a t T u n e D e l u x e {
8 // Entry point .
9 public static void main ( String [] args ) {
10 while (! StdIn . isEmpty ()) {
11 int pitch = StdIn . readInt ();
12 double duration = StdIn . readDouble ();
25 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java P la y T h at T u n e De l u x e < ../ data / elise . txt
$ _
& ~/workspace/ipj/programs
$ java GaussianTable 1019 209
400 0.0015
500 0.0065
600 0.0225
700 0.0635
800 0.1474
900 0.2845
1000 0.4638
26 / 78
Introduction to Programming in Java
1100 0.6508
1200 0.8068
1300 0.9106
1400 0.9658
1500 0.9893
1600 0.9973
$ _
2.2.2 Gaussian.java
L Gaussian.java
1 // A library of Gaussian functions .
2
3 import stdlib . StdOut ;
4
5 public class Gaussian {
6 // Returns the value of the Gaussian probability density function with mean 0 and standard
7 // deviation 1 at the given z value .
8 public static double pdf ( double z ) {
9 return Math . exp ( - z * z / 2) / Math . sqrt (2 * Math . PI );
10 }
11
12 // Returns the value of the Gaussian probability density function with mean mu and standard
13 // deviation sigma at the given x value .
14 public static double pdf ( double x , double mu , double sigma ) {
15 double z = ( x - mu ) / sigma ;
16 return pdf ( z ) / sigma ;
17 }
18
19 // Returns the value of the Gaussian cumulative distribution function with mean 0 and
20 // standard deviation 1 at the given z value .
21 public static double cdf ( double z ) {
22 if ( z < -8.0) {
23 return 0.0;
24 }
25 if ( z > 8.0) {
26 return 1.0;
27 }
28 double total = 0.0;
29 double term = z ;
30 int i = 3;
31 while ( total != total + term ) {
32 total += term ;
33 term *= z * z / i ;
34 i += 2;
35 }
36 return 0.5 + total * pdf ( z );
37 }
38
39 // Returns the value of the Gaussian cumulative distribution function with mean mu and
40 // standard deviation sigma at the given x value .
41 public static double cdf ( double x , double mu , double sigma ) {
42 double z = ( x - mu ) / sigma ;
43 return cdf ( z );
44 }
45
46 // Unit tests the library .
47 public static void main ( String [] args ) {
48 double x = Double . parseDouble ( args [0]);
49 double mu = Double . parseDouble ( args [1]);
50 double sigma = Double . parseDouble ( args [2]);
51 StdOut . println ( cdf (x , mu , sigma ));
52 }
53 }
& ~/workspace/ipj/programs
$ java Gaussian 820 1019 209
0 . 1 7 0 5 0 9 6 6 8 6 9 1 3 2 10 6
$ java Gaussian 1500 1019 209
0 . 9 8 9 3 1 6 4 83 7 3 8 38 8 5
$ java Gaussian 1500 1025 231
0 . 9 8 0 1 2 2 0 90 7 3 6 54 9 1
$ _
27 / 78
Introduction to Programming in Java
2.2.3 IFS.java
L IFS.java
1 // Accepts n ( int ) as a command - line argument , a 1 - by - m vector ( probabilities ) and two m - by -3
2 // matrices ( coefficients for updating x and y , respectively ) from standard input ; and plots the
3 // results as a set of n points using standard draw .
4
5 import stdlib . StdArrayIO ;
6 import stdlib . StdDraw ;
7 import stdlib . StdRandom ;
8
9 public class IFS {
10 // Entry point .
11 public static void main ( String [] args ) {
12 int n = Integer . parseInt ( args [0]);
13 double [] dist = StdArrayIO . readDouble1D ();
14 double [][] cx = StdArrayIO . readDouble2D ();
15 double [][] cy = StdArrayIO . readDouble2D ();
16 double x = 0.0 , y = 0.0;
17 StdDraw . e n a b l e D o u b l e B u f f e r i n g ();
18 for ( int i = 0; i < n ; i ++) {
19 int r = StdRandom . discrete ( dist );
20 double [] col = {x , y , 1};
21 double x0 = Matrix . dot ( Matrix . row ( cx , r ) , col );
22 double y0 = Matrix . dot ( Matrix . row ( cy , r ) , col );
23 x = x0 ;
24 y = y0 ;
25 StdDraw . point (x , y );
26 }
27 StdDraw . show ();
28 }
29 }
& ~/workspace/ipj/programs
$ java IFS 100000 < ../ data / sierpinski . txt
$ _
2.2.4 Matrix.java
L Matrix.java
1 // A library of matrix functions .
2
3 import java . util . Arrays ;
4
5 import stdlib . StdOut ;
6
7 public class Matrix {
8 // Returns the ith row of matrix a .
9 public static double [] row ( double [][] a , int i ) {
10 return a [ i ];
11 }
12
28 / 78
Introduction to Programming in Java
29 / 78
Introduction to Programming in Java
93 }
94 }
& ~/workspace/ipj/programs
$ java Matrix
a = [[1.0 , 2.0 , 3.0] , [4.0 , 5.0 , 6.0] , [7.0 , 8.0 , 9.0]]
b = [[1.0] , [2.0] , [3.0]]
row (a , 1) = [4.0 , 5.0 , 6.0]
col (a , 1) = [2.0 , 5.0 , 8.0]
add (a , a ) = [[2.0 , 4.0 , 6.0] , [8.0 , 10.0 , 12.0] , [14.0 , 16.0 , 18.0]]
subtract (a , a ) = [[0.0 , 0.0 , 0.0] , [0.0 , 0.0 , 0.0] , [0.0 , 0.0 , 0.0]]
multiply (a , b ) = [[14.0] , [32.0] , [50.0]]
transpose ( b ) = [[1.0 , 2.0 , 3.0]]
$ _
2.3 Recursion
2.3.1 Factorial.java
L Factorial.java
1 // Accepts n ( int ) as command - line argument ; and writes n ! to standard output .
2
3 import stdlib . StdOut ;
4
5 public class Factorial {
6 // Entry point .
7 public static void main ( String [] args ) {
8 int n = Integer . parseInt ( args [0]);
9 StdOut . println ( factorial ( n ));
10 }
11
12 // Returns n ! computed recursively .
13 private static int factorial ( int n ) {
14 if ( n == 0) {
15 return 1;
16 }
17 return n * factorial ( n - 1);
18 }
19 }
& ~/workspace/ipj/programs
$ java Factorial 0
1
$ java Factorial 5
120
$ _
2.3.2 Euclid.java
L Euclid.java
1 // Accepts p ( int ) and q ( int ) as command - line arguments ; and writes gcd (p , q ) to standard output .
2
3 import stdlib . StdOut ;
4
5 public class Euclid {
6 // Entry point .
7 public static void main ( String [] args ) {
8 int p = Integer . parseInt ( args [0]);
9 int q = Integer . parseInt ( args [1]);
10 StdOut . println ( gcd (p , q ));
11 }
12
13 // Returns the gcd of p and q computed recursively using Euclid ’s algorithm .
14 private static int gcd ( int p , int q ) {
15 if ( q == 0) {
16 return p ;
17 }
18 return gcd (q , p % q );
19 }
20 }
30 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Euclid 1440 408
24
$ java Euclid 314159 271828
1
$ _
2.3.3 TowersOfHanoi.java
L TowersOfHanoi.java
1 // Accepts n ( int ) as command - line argument ; and writes to standard output the instructions to
2 // move n Towers of Hanoi disks to the left .
3
4 import stdlib . StdOut ;
5
6 public class TowersOfHanoi {
7 // Entry point .
8 public static void main ( String [] args ) {
9 int n = Integer . parseInt ( args [0]);
10 moves (n , true );
11 }
12
13 // Writes to standard output the instructions to move n Towers of Hanoi disks to the left ( if
14 // parameter left is true ) or to the right ( if parameter left is false ).
15 private static void moves ( int n , boolean left ) {
16 if ( n == 0) {
17 return ;
18 }
19 moves ( n - 1 , ! left );
20 if ( left ) {
21 StdOut . println ( n + " left " );
22 } else {
23 StdOut . println ( n + " right " );
24 }
25 moves ( n - 1 , ! left );
26 }
27 }
& ~/workspace/ipj/programs
$ java TowersOfHanoi 1
1 left
$ java TowersOfHanoi 2
1 right
2 left
1 right
$ java TowersOfHanoi 3
1 left
2 right
1 left
3 left
1 left
2 right
1 left
$ java TowersOfHanoi 4
1 right
2 left
1 right
3 right
1 right
2 left
1 right
4 left
1 right
2 left
1 right
3 right
1 right
2 left
1 right
$ _
31 / 78
Introduction to Programming in Java
2.3.4 HTree.java
L HTree.java
1 // Accepts n ( int ) as a command - line argument ; and draws using standard draw a level n H - tree
2 // centered at (0.5 , 0.5) with lines of length 0.5.
3
4 import stdlib . StdDraw ;
5
6 public class HTree {
7 // Entry point .
8 public static void main ( String [] args ) {
9 int n = Integer . parseInt ( args [0]);
10 StdDraw . setPenRadius (0.001);
11 draw (n , 0.5 , 0.5 , 0.5);
12 StdDraw . show ();
13 }
14
15 // Draws to standard draw a level n H - tree centered at (x , y ) with lines of length
16 // lineLength .
17 private static void draw ( int n , double lineLength , double x , double y ) {
18 if ( n == 0) {
19 return ;
20 }
21 double x0 = x - lineLength / 2;
22 double x1 = x + lineLength / 2;
23 double y0 = y - lineLength / 2;
24 double y1 = y + lineLength / 2;
25 StdDraw . line ( x0 , y , x1 , y );
26 StdDraw . line ( x0 , y0 , x0 , y1 );
27 StdDraw . line ( x1 , y0 , x1 , y1 );
28 draw ( n - 1 , lineLength / 2 , x0 , y0 );
29 draw ( n - 1 , lineLength / 2 , x0 , y1 );
30 draw ( n - 1 , lineLength / 2 , x1 , y0 );
31 draw ( n - 1 , lineLength / 2 , x1 , y1 );
32 }
33 }
& ~/workspace/ipj/programs
$ java HTree 5
$ _
2.3.5 Fibonacci.java
L Fibonacci.java
1 // Accepts n ( int ) as command - line argument ; and writes the nth Fibonacci number to standard output .
2
3 import stdlib . StdOut ;
4
5 public class Fibonacci {
6 // Entry point .
7 public static void main ( String [] args ) {
8 int n = Integer . parseInt ( args [0]);
32 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Fibonacci 0
0
$ java Fibonacci 1
1
$ java Fibonacci 2
1
$ java Fibonacci 3
2
$ java Fibonacci 10
55
$ _
& ~/workspace/ipj/programs
$ java PercolationIO 10 0.8
$ _
33 / 78
Introduction to Programming in Java
2.4.2 Percolation.java
L Percolation.java
1 // A library of percolation functions .
2
3 import stdlib . StdArrayIO ;
4 import stdlib . StdOut ;
5
6 public class Percolation {
7 // Computes and returns the full sites of the given percolation system .
8 public static boolean [][] flow ( boolean [][] isOpen ) {
9 int n = isOpen . length ;
10 boolean [][] isFull = new boolean [ n ][ n ];
11 for ( int j = 0; j < n ; j ++) {
12 flow ( isOpen , isFull , 0 , j );
13 }
14 return isFull ;
15 }
16
17 // Given the full sites of a percolation system , returns true if the system percolates , and
18 // false otherwise .
19 public static boolean percolates ( boolean [][] isFull ) {
20 int n = isFull . length ;
21 for ( int j = 0; j < n ; j ++) {
22 if ( isFull [ n - 1][ j ]) {
23 return true ;
24 }
25 }
26 return false ;
27 }
28
29 // Given the open and full sites of a percolation system , updates the full sites by marking
30 // every site of that system that is open and reachable from site (i , j ).
31 private static void flow ( boolean [][] isOpen , boolean [][] isFull , int i , int j ) {
32 int n = isOpen . length ;
33 if ( i < 0 || i >= n || j < 0 || j >= n ) {
34 return ;
35 }
36 if (! isOpen [ i ][ j ] || isFull [ i ][ j ]) {
37 return ;
38 }
39 isFull [ i ][ j ] = true ;
40 flow ( isOpen , isFull , i + 1 , j );
41 flow ( isOpen , isFull , i , j + 1);
42 flow ( isOpen , isFull , i , j - 1);
43 flow ( isOpen , isFull , i - 1 , j );
44 }
45
46 // Unit tests the library .
47 public static void main ( String [] args ) {
48 boolean [][] isOpen = StdArrayIO . readBoolean2D ();
49 boolean [][] isFull = flow ( isOpen );
50 StdArrayIO . print ( isFull );
51 StdOut . println ( percolates ( isFull ));
52 }
53 }
34 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Percolation < ../ data / test5 . txt
5 5
0 1 1 0 1
0 0 1 1 1
0 0 0 1 1
0 0 0 0 1
0 1 1 1 1
true
$ java Percolation < ../ data / test8 . txt
8 8
0 0 1 1 1 0 0 0
0 0 0 1 1 1 1 1
0 0 0 0 0 1 1 0
0 0 0 0 0 1 1 1
0 0 0 0 0 1 1 0
0 0 0 0 0 0 1 1
0 0 0 0 1 1 1 1
0 0 0 0 0 1 0 0
true
$ _
2.4.3 Visualize.java
L Visualize.java
1 // Accepts n ( int ) , p ( double ) , and trials ( int ) as command - line arguments ; generates an n - by - n
2 // random percolation system with vacancy probability p ; computes the directed percolation flow ;
3 // and draws the result trials times using standard draw .
4
5 import stdlib . StdDraw ;
6
7 public class Visualize {
8 // Entry point .
9 public static void main ( String [] args ) {
10 int n = Integer . parseInt ( args [0]);
11 double p = Double . parseDouble ( args [1]);
12 int trials = Integer . parseInt ( args [2]);
13 for ( int i = 0; i < trials ; i ++) {
14 boolean [][] isOpen = PercolationIO . random (n , p );
15 StdDraw . clear ();
16 StdDraw . setPenColor ( StdDraw . BLACK );
17 PercolationIO . draw ( isOpen , false );
18 StdDraw . setPenColor ( StdDraw . BLUE );
19 boolean [][] isFull = Percolation . flow ( isOpen );
20 PercolationIO . draw ( isFull , true );
21 StdDraw . pause (1000);
22 }
23 }
24 }
& ~/workspace/ipj/programs
$ java Visualize 20 0.65 1
$ _
35 / 78
Introduction to Programming in Java
2.4.4 Estimate.java
L Estimate.java
1 // Accepts n ( int ) , p ( double ) , and trials ( int ) as command - line arguments ; creates trials random
2 // n - by - n percolation systems with vacancy probability p ; determines the fraction of them that
3 // percolates ; and writes that fraction to standard output .
4
5 import stdlib . StdOut ;
6
7 public class Estimate {
8 // Entry point .
9 public static void main ( String [] args ) {
10 int n = Integer . parseInt ( args [0]);
11 double p = Double . parseDouble ( args [1]);
12 int trials = Integer . parseInt ( args [2]);
13 StdOut . println ( evaluate (n , p , trials ));
14 }
15
16 // Generates a random n - by - n percolation system with vacancy probability p and determines if
17 // the system percolates . Repeats trials times . Returns an estimate of the empirical
18 // percolation probability of such systems .
19 public static double evaluate ( int n , double p , int trials ) {
20 int count = 0;
21 for ( int i = 0; i < trials ; i ++) {
22 boolean [][] isOpen = PercolationIO . random (n , p );
23 boolean [][] isFull = Percolation . flow ( isOpen );
24 if ( Percolation . percolates ( isFull )) {
25 count ++;
26 }
27 }
28 return 1.0 * count / trials ;
29 }
30 }
& ~/workspace/ipj/programs
$ java Estimate 20 0.55 100
0.26
$ java Estimate 20 0.65 100
0.87
$ java Estimate 40 0.55 100
0.09
$ java Estimate 40 0.65 100
0.97
$ _
2.4.5 PercolationPlot.java
L PercolationPlot.java
1 // Accepts n ( int ) as command - line argument ; and draws using standard draw a plot of the percolation
2 // probability ( experimental observation ) against the vacancy probability ( control variable ).
3
4 import stdlib . StdDraw ;
5
6 public class Percola ti on P lo t {
7 // Entry point .
8 public static void main ( String [] args ) {
9 int n = Integer . parseInt ( args [0]);
10 StdDraw . setCanvasSize (750 , 750);
11 StdDraw . setXscale ( -0.2 , 1.2);
12 StdDraw . setYscale ( -0.2 , 1.2);
13 StdDraw . setPenRadius (0.0);
14 StdDraw . square (0.5 , 0.5 , 0.52);
15 StdDraw . setPenColor ( StdDraw . WHITE );
16 StdDraw . filledSquare (0.5 , 0.5 , 0.51);
17 StdDraw . setPenColor ( StdDraw . BLACK );
18 StdDraw . text (0.5 , -0.1 , " Vacancy Probability " );
19 StdDraw . text ( -0.11 , 0.5 , " Percolation " );
20 StdDraw . text ( -0.11 , 0.45 , " Probability " );
21 curve (n , 0.0 , 0.0 , 1.0 , 1.0 , 10000 , 0.01 , 0.0025);
22 }
23
24 // Plots the percolation curve ( percolation probability vs vacancy probability ) recursively .
25 private static void curve ( int n , double x0 , double y0 , double x1 , double y1 ,
26 int trials , double gap , double error ) {
36 / 78
Introduction to Programming in Java
27 double xm = ( x0 + x1 ) / 2;
28 double ym = ( y0 + y1 ) / 2;
29 double fxm = Estimate . evaluate (n , xm , trials );
30 if ( x1 - x0 < gap || Math . abs ( ym - fxm ) < error ) {
31 StdDraw . line ( x0 , y0 , x1 , y1 );
32 return ;
33 }
34 curve (n , x0 , y0 , xm , fxm , trials , gap , error );
35 StdDraw . filledCircle ( xm , fxm , 0.005);
36 if ( xm > 0.55 && xm < 0.6) {
37 String xyLabel = String . format ( " (%.3 f , %.3 f ) " , xm , fxm );
38 StdDraw . text ( xm + 0.1 , fxm , xyLabel );
39 }
40 curve (n , xm , fxm , x1 , y1 , trials , gap , error );
41 }
42 }
& ~/workspace/ipj/programs
$ java Percolat io nP lot 20
$ _
3 Object-oriented Programming
3.1 Using Data Types
3.1.1 PotentialGene.java
L PotentialGene.java
1 // Accepts dna ( String ) as command - line argument ; and writes to to standard output whether dna
2 // corresponds to a potential gene or not .
3
4 import stdlib . StdOut ;
5
6 public class PotentialGene {
7 // Entry point .
8 public static void main ( String [] args ) {
9 String dna = args [0];
10 StdOut . println ( is Po te n ti al Ge n e ( dna ));
11 }
12
13 // Returns true if dna corresponds to a potential gene , and false otherwise .
14 private static boolean i sP ot e nt ia lG e ne ( String dna ) {
15 String ATG = " ATG " , TAA = " TAA " , TAG = " TAG " , TGA = " TGA " ;
16 if ( dna . length () % 3 != 0) {
17 return false ;
18 }
19 if (! dna . startsWith ( ATG )) {
20 return false ;
21 }
22 for ( int i = 3; i < dna . length () - 3; i ++) {
23 if ( i % 3 == 0) {
24 String codon = dna . substring (i , i + 3);
37 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java PotentialGene A T G C G C C T G C G T C T G T A C T A G
true
$ java PotentialGene A T G C G C T G C G T C T G T A C T A G
false
$ _
3.1.2 AlbersSquares.java
L AlbersSquares.java
1 // Accepts r1 ( int ) , g1 ( int ) , b1 ( int ) , r2 ( int ) , g2 ( int ) , and b2 ( int ) as command - line
2 // arguments ; and draws using standard draw Albers ’ squares with colors ( r1 , g1 , b1 ) and ( r2 , g2 ,
3 // b2 ).
4
5 import java . awt . Color ;
6
7 import stdlib . StdDraw ;
8
9 public class AlbersSquares {
10 // Entry point .
11 public static void main ( String [] args ) {
12 int r1 = Integer . parseInt ( args [0]);
13 int g1 = Integer . parseInt ( args [1]);
14 int b1 = Integer . parseInt ( args [2]);
15 int r2 = Integer . parseInt ( args [3]);
16 int g2 = Integer . parseInt ( args [4]);
17 int b2 = Integer . parseInt ( args [5]);
18 Color c1 = new Color ( r1 , g1 , b1 );
19 Color c2 = new Color ( r2 , g2 , b2 );
20 StdDraw . setCanvasSize (512 , 256);
21 StdDraw . setYscale (0.25 , 0.75);
22 StdDraw . setPenColor ( c1 );
23 StdDraw . filledSquare (0.25 , 0.5 , 0.2);
24 StdDraw . setPenColor ( c2 );
25 StdDraw . filledSquare (0.25 , 0.5 , 0.1);
26 StdDraw . setPenColor ( c2 );
27 StdDraw . filledSquare (0.75 , 0.5 , 0.2);
28 StdDraw . setPenColor ( c1 );
29 StdDraw . filledSquare (0.75 , 0.5 , 0.1);
30 StdDraw . show ();
31 }
32 }
& ~/workspace/ipj/programs
$ java AlbersSquares 0 174 239 147 149 252
$ _
38 / 78
Introduction to Programming in Java
3.1.3 Luminance.java
L Luminance.java
1 // A library of color - related functions .
2
3 import java . awt . Color ;
4
5 import stdlib . StdOut ;
6
7 public class Luminance {
8 // Returns the luminance of the Color c .
9 public static double luminance ( Color c ) {
10 int r = c . getRed ();
11 int g = c . getGreen ();
12 int b = c . getBlue ();
13 if ( r == g && r == b ) {
14 return r ;
15 }
16 return 0.299 * r + 0.587 * g + 0.114 * b ;
17 }
18
19 // Returns the grayscale equivalent of Color c .
20 public static Color toGray ( Color c ) {
21 int y = ( int ) ( Math . round ( luminance ( c )));
22 Color gray = new Color (y , y , y );
23 return gray ;
24 }
25
26 // Returns true if Color c1 is compatible with Color c2 , and false otherwise .
27 public static boolean areCompatible ( Color c1 , Color c2 ) {
28 return Math . abs ( luminance ( c1 ) - luminance ( c2 )) >= 128.0;
29 }
30
31 // Unit tests the library .
32 public static void main ( String [] args ) {
33 int r1 = Integer . parseInt ( args [0]);
34 int g1 = Integer . parseInt ( args [1]);
35 int b1 = Integer . parseInt ( args [2]);
36 int r2 = Integer . parseInt ( args [3]);
37 int g2 = Integer . parseInt ( args [4]);
38 int b2 = Integer . parseInt ( args [5]);
39 Color c1 = new Color ( r1 , g1 , b1 );
40 Color c2 = new Color ( r2 , g2 , b2 );
41 StdOut . println ( c1 + " compatible with " + c2 + " ? " + areCompatible ( c1 , c2 ));
42 }
43 }
& ~/workspace/ipj/programs
$ java Luminance 0 0 0 0 0 255
java . awt . Color [ r =0 , g =0 , b =0] compatible with java . awt . Color [ r =0 , g =0 , b =255]? false
$ _
3.1.4 Grayscale.java
L Grayscale.java
1 // Accepts filename ( String ) as command - line argument ; and reads an image from a file with that
2 // name ; and renders a gray scale version of that image .
3
4 import java . awt . Color ;
5
6 import stdlib . Picture ;
7
8 public class Grayscale {
9 // Entry point .
10 public static void main ( String [] args ) {
11 String filename = args [0];
12 Picture picture = new Picture ( filename );
13 for ( int col = 0; col < picture . width (); col ++) {
14 for ( int row = 0; row < picture . height (); row ++) {
15 Color pixel = picture . get ( col , row );
16 Color gray = Luminance . toGray ( pixel );
17 picture . set ( col , row , gray );
18 }
19 }
39 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Grayscale ../ data / mandrill . jpg
$ _
3.1.5 Fade.java
L Fade.java
1 // Accepts sourceFile ( String ) , targetFile ( String ) , and n ( int ) as command - line arguments ; reads
2 // images from sourceFile and targetFile ; over the course of n frames , gradually replaces the
3 // image from sourceFile with the image from targetFile ; and displays each intermediate image
4 // using standard draw .
5
6 import java . awt . Color ;
7
8 import stdlib . Picture ;
9 import stdlib . StdDraw ;
10
11 public class Fade {
12 // Entry point .
13 public static void main ( String [] args ) {
14 String sourceFile = args [0];
15 String targetFile = args [1];
16 int n = Integer . parseInt ( args [2]);
17 Picture source = new Picture ( sourceFile );
18 Picture target = new Picture ( targetFile );
19 int width = source . width ();
20 int height = source . height ();
21 Picture picture = new Picture ( width , height );
22 for ( int i = 0; i <= n ; i ++) {
23 for ( int col = 0; col < width ; col ++) {
24 for ( int row = 0; row < height ; row ++) {
25 Color c0 = source . get ( col , row );
26 Color cn = target . get ( col , row );
27 double alpha = 1.0 * i / n ;
28 Color c = blend ( c0 , cn , alpha );
29 picture . set ( col , row , c );
30 }
31 }
32 picture . show ();
33 StdDraw . pause (10000);
34 }
35 }
36
37 // Returns a new Color object which blends Color objects c1 and c2 using alpha as the
38 // blending factor .
39 private static Color blend ( Color c1 , Color c2 , double alpha ) {
40 int r = ( int ) ((1 - alpha ) * c1 . getRed () + alpha * c2 . getRed ());
41 int g = ( int ) ((1 - alpha ) * c1 . getGreen () + alpha * c2 . getGreen ());
42 int b = ( int ) ((1 - alpha ) * c1 . getBlue () + alpha * c2 . getBlue ());
40 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Fade ../ data / mandrill . jpg ../ data / darwin . jpg 5
$ _
3.1.6 Cat.java
L Cat.java
1 // Accepts args [0: n -2] files or web pages as command - line arguments ; and copies them to the file
2 // whose name is accepted as command - line argument args [ n - 1].
3
4 import stdlib . In ;
5 import stdlib . Out ;
6
7 public class Cat {
8 // Entry point .
9 public static void main ( String [] args ) {
10 int n = args . length ;
11 Out outStream = new Out ( args [ n - 1]);
12 for ( int i = 0; i < n - 1; i ++) {
13 In inStream = new In ( args [ i ]);
14 String s = inStream . readAll ();
15 outStream . print ( s );
16 }
17 }
18 }
& ~/workspace/ipj/programs
$ cat ../ data / in1 . txt
This is
$ cat ../ data / in2 . txt
a tiny
test .
$ java Cat ../ data / in1 . txt ../ data / in2 . txt out . txt
$ cat out . txt
This is
a tiny
test .
$ _
3.1.7 Split.java
L Split.java
1 // Accepts filename ( String ) and n ( int ) as command - line arguments ; and splits the file whose
2 // name is filename . csv , by field , into n files named filename1 . txt , filename2 . txt , etc .
3
4 import stdlib . In ;
5 import stdlib . Out ;
6
7 public class Split {
8 // Entry point .
9 public static void main ( String [] args ) {
10 String filename = args [0];
11 int n = Integer . parseInt ( args [1]);
41 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ head -5 ../ data / ip . csv
www . princeton . edu ,1 28 . 11 2. 12 8 .1 5
www . cs . princeton . edu , 12 8 .1 12 . 13 6. 35
www . math . princeton . edu ,1 28.112. 18.11
www . cs . harvard . edu ,1 4 0. 24 7 .5 0. 12 7
www . harvard . edu ,128.1 03.60.2 4
$ java Split ../ data / ip 2
$ head -5 ../ data / ip1 . txt
www . princeton . edu
www . cs . princeton . edu
www . math . princeton . edu
www . cs . harvard . edu
www . harvard . edu
$ head -5 ../ data / ip2 . txt
128. 112.128.15
128. 112.136.35
128.112.18.11
140. 247.50.127
128.103.60.24
$ _
& ~/workspace/ipj/programs
$ java TimeOps 10000000
Math . sqrt () is 2.58 times faster than Math . pow ()
$ _
42 / 78
Introduction to Programming in Java
3.2.2 Stopwatch.java
L Stopwatch.java
1 // An immutable data type to measure the running ( wall clock ) time of a program .
2
3 import stdlib . StdOut ;
4
5 public class Stopwatch {
6 private long creationTime ; // creation time of stopwatch
7
8 // Constructs a new stopwatch .
9 public Stopwatch () {
10 creationTime = System . c u r r e n t T i m e M i l l i s ();
11 }
12
13 // Returns the elapsed time ( in seconds ) since creation .
14 public double elapsedTime () {
15 return ( System . c u r r e n t T i m e M i l l i s () - creationTime ) / 1000.0;
16 }
17
18 // Returns a string re present ation of this stopwatch .
19 public String toString () {
20 return " " + elapsedTime ();
21 }
22
23 // Unit tests the data type .
24 public static void main ( String [] args ) {
25 int n = Integer . parseInt ( args [0]);
26 Stopwatch watch = new Stopwatch ();
27 int primes = 0;
28 for ( int i = 2; i <= n ; i ++) {
29 int j = 2;
30 while ( j <= i / j ) {
31 if ( i % j == 0) {
32 break ;
33 }
34 j ++;
35 }
36 if ( j > i / j ) {
37 primes ++;
38 }
39 }
40 double time = watch . elapsedTime ();
41 StdOut . printf ( " pi (% d ) = % d computed in %.5 f seconds \ n " , n , primes , time );
42 }
43 }
& ~/workspace/ipj/programs
$ java Stopwatch 1000000
pi (1000000) = 78498 computed in 0.33000 seconds
$ _
3.2.3 Bernoulli.java
L Bernoulli.java
1 // Accepts n ( int ) , p ( double ) , and trials ( int ) as command - line arguments ; performs trials
2 // experiments , each of which counts the number of heads found when a coin with bias p is
3 // flipped n times ; and draws the results using standard draw .
4
5 import stdlib . StdRandom ;
6
7 public class Bernoulli {
8 // Flips a coin with bias p a total of n times and returns the number of heads obtained .
9 private static int binomial ( int n , double p ) {
10 int heads = 0;
11 for ( int i = 0; i < n ; i ++) {
12 if ( StdRandom . bernoulli ( p )) {
13 heads ++;
14 }
15 }
16 return heads ;
17 }
18
19 // Entry point .
43 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Bernoulli 100 0.5 10000
$ _
3.2.4 Histogram.java
L Histogram.java
1 // A data type that represents histograms of the frequency of occurrence of values in [0 , n ).
2
3 import java . util . Arrays ;
4
5 import stdlib . StdDraw ;
6 import stdlib . StdRandom ;
7 import stdlib . StdStats ;
8
9 public class Histogram {
10 private double [] freq ; // array of frequencies
11
12 // Constructs a histogram to store frequency of occurrence of values [0 , n ).
13 public Histogram ( int n ) {
14 freq = new double [ n ];
15 }
16
17 // Adds one occurrence of the value i .
18 public void addDataPoint ( int i ) {
19 freq [ i ]++;
20 }
21
22 // Draws this histogram to standard draw .
23 public void draw () {
24 StdDraw . setYscale ( -1 , StdStats . max ( freq ) + 1);
25 StdStats . plotBars ( freq );
26 }
27
28 // Returns a string re present ation of this histogram .
29 public String toString () {
30 return Arrays . toString ( freq );
31 }
32
33 // Unit tests the data type .
34 public static void main ( String [] args ) {
44 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Histogram 1000
$ _
3.2.5 Drunks.java
L Drunks.java
1 // Accepts n ( int ) , steps ( int ) , and stepSize ( double ) as command - line arguments ; creates n
2 // Turtle objects ; and has the turtles take steps random steps , each of size stepSize .
3
4 import stdlib . StdDraw ;
5 import stdlib . StdRandom ;
6
7 public class Drunks {
8 // Entry point .
9 public static void main ( String [] args ) {
10 int n = Integer . parseInt ( args [0]);
11 int steps = Integer . parseInt ( args [1]);
12 double stepSize = Double . parseDouble ( args [2]);
13 Turtle [] turtles = new Turtle [ n ];
14 for ( int i = 0; i < n ; i ++) {
15 double x = StdRandom . uniform (0.0 , 1.0);
16 double y = StdRandom . uniform (0.0 , 1.0);
17 double theta = StdRandom . uniform (0.0 , 360.0);
18 turtles [ i ] = new Turtle (x , y , theta );
19 }
20 StdDraw . setPenRadius (0.001);
21 StdDraw . e n a b l e D o u b l e B u f f e r i n g ();
22 for ( int i = 0; i < steps ; i ++) {
23 for ( Turtle turtle : turtles ) {
24 double theta = StdRandom . uniform (0.0 , 360.0);
25 turtle . turnLeft ( theta );
26 turtle . goForward ( stepSize );
27 StdDraw . show ();
28 }
29 }
30 }
31 }
& ~/workspace/ipj/programs
$ java Drunks 20 1000 0.01
$ _
45 / 78
Introduction to Programming in Java
3.2.6 Turtle.java
L Turtle.java
1 // A data type for turtle graphics using standard draw .
2
3 import stdlib . StdDraw ;
4
5 public class Turtle {
6 private double x ; // x - coordinate of turtle
7 private double y ; // y - coordinate of turtle
8 private double theta ; // ccw angle ( in degrees ) of turtle
9
10 // Constructs a turtle given its coordinates and angle .
11 public Turtle ( double x , double y , double theta ) {
12 this . x = x ;
13 this . y = y ;
14 this . theta = theta ;
15 }
16
17 // Rotates this turtle by theta in ccw direction .
18 public void turnLeft ( double theta ) {
19 this . theta += theta ;
20 }
21
22 // Moves this turtle forward by given amount , with the pen down .
23 public void goForward ( double stepSize ) {
24 double xOld = x ;
25 double yOld = y ;
26 x += stepSize * Math . cos ( Math . toRadians ( theta ));
27 y += stepSize * Math . sin ( Math . toRadians ( theta ));
28 StdDraw . line ( xOld , yOld , x , y );
29 }
30
31 // Returns a string re present ation of this turtle .
32 public String toString () {
33 return " ( " + x + " , " + y + " , " + theta + " ) " ;
34 }
35
36 // Unit tests the data type .
37 public static void main ( String [] args ) {
38 int n = Integer . parseInt ( args [0]);
39 Turtle turtle = new Turtle (0.5 , 0.0 , 180.0 / n );
40 double stepSize = Math . sin ( Math . toRadians (180.0 / n ));
41 StdDraw . setPenRadius (0.001);
42 for ( int i = 0; i < n ; i ++) {
43 turtle . goForward ( stepSize );
44 turtle . turnLeft (360.0 / n );
45 }
46 StdDraw . show ();
47 }
48 }
& ~/workspace/ipj/programs
$ java Turtle 10
$ _
46 / 78
Introduction to Programming in Java
47 / 78
Introduction to Programming in Java
51 if ( other == null ) {
52 return false ;
53 }
54 if ( other == this ) {
55 return true ;
56 }
57 if ( other . getClass () != this . getClass ()) {
58 return false ;
59 }
60 Complex a = this , b = ( Complex ) other ;
61 return a . re == b . re && a . im == b . im ;
62 }
63
64 // Returns a string re present ation of this complex number .
65 public String toString () {
66 String SUFFIX = " i " ;
67 if ( im == 0) {
68 return re + " " ;
69 } else if ( re == 0) {
70 return im + SUFFIX ;
71 } else if ( im < 0) {
72 return re + " - " + ( - im ) + SUFFIX ;
73 } else {
74 return re + " + " + im + SUFFIX ;
75 }
76 }
77
78 // Unit tests the data type .
79 public static void main ( String [] args ) {
80 Complex a = new Complex (5.0 , -6.0);
81 Complex b = new Complex (3.0 , 4.0);
82 StdOut . println ( " a = " + a );
83 StdOut . println ( " b = " + b );
84 StdOut . println ( " conj ( a ) = " + a . conjugate ());
85 StdOut . println ( " a + b = " + a . add ( b ));
86 StdOut . println ( " a * b = " + a . multiply ( b ));
87 StdOut . println ( " | b | = " + b . abs ());
88 }
89 }
& ~/workspace/ipj/programs
$ java Complex
a = 5.0 - 6.0 i
b = 3.0 + 4.0 i
conj ( a ) = 5.0 + 6.0 i
a + b = 8.0 - 2.0 i
a * b = 39.0 + 2.0 i
|b| = 5.0
$ _
3.3.2 Mandelbrot.java
L Mandelbrot.java
1 // Accepts xc ( double ) , yc ( double ) , and size ( double ) as command - line arguments ; and draws using
2 // standard draw the size - by - size region of the Mandelbrot set , centered at ( xc , yc ).
3
4 import java . awt . Color ;
5
6 import stdlib . Picture ;
7
8 public class Mandelbrot {
9 // Entry point .
10 public static void main ( String [] args ) {
11 double xc = Double . parseDouble ( args [0]);
12 double yc = Double . parseDouble ( args [1]);
13 double size = Double . parseDouble ( args [2]);
14 int N = 512;
15 int ITERATIONS = 255;
16 Picture picture = new Picture (N , N );
17 for ( int col = 0; col < N ; col ++) {
18 for ( int row = 0; row < N ; row ++) {
19 double x0 = xc - size / 2 + size * col / N ;
20 double y0 = yc - size / 2 + size * row / N ;
21 Complex z0 = new Complex ( x0 , y0 );
22 int gray = ITERATIONS - mandel ( z0 , ITERATIONS );
23 Color color = new Color ( gray , gray , gray );
48 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Mandelbrot -0.5 0 2
$ _
3.3.3 Vector.java
L Vector.java
1 // An immutable data type to represent an n - dimensional vector .
2
3 import java . util . Arrays ;
4
5 import stdlib . StdOut ;
6
7 public class Vector {
8 private int n ; // dimension of vector
9 private double [] coords ; // array of components
10
11 // Constructs a vector given its components .
12 public Vector ( double [] coords ) {
13 n = coords . length ;
14 this . coords = new double [ n ]; // defensive copy of array of components
15 for ( int i = 0; i < n ; i ++) {
16 this . coords [ i ] = coords [ i ];
17 }
18 }
19
20 // Returns the ith component of this vector .
21 public double get ( int i ) {
22 return coords [ i ];
23 }
24
25 // Returns the sum of this and the other vector .
26 public Vector add ( Vector other ) {
27 double [] result = new double [ n ];
28 for ( int i = 0; i < n ; i ++) {
49 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Vector
x = [1.0 , 2.0 , 3.0 , 4.0]
y = [5.0 , 2.0 , 4.0 , 1.0]
x + y = [6.0 , 4.0 , 7.0 , 5.0]
x - y = [ -4.0 , 0.0 , -1.0 , 3.0]
x dot y = 25.0
10 x = [10.0 , 20.0 , 30.0 , 40.0]
xhat = [0.18257418583505536 , 0.3651483716701107 , 0.5477225575051661 , 0 . 7 3 0 2 9 6 7 4 3 3 4 0 2 2 1 4 ]
50 / 78
Introduction to Programming in Java
|x| = 5 .4 7 72 2 55 7 5 0 5 1 6 6 1
ydim = 4
$ _
3.3.4 Sketch.java
L Sketch.java
1 // An immutable data type that represents a profile of a string , as a d - dimensional unit vector .
2
3 import stdlib . StdIn ;
4 import stdlib . StdOut ;
5
6 public class Sketch {
7 private Vector sketch ; // string profile as a d - dimensional unit vector
8
9 // Constructs a new sketch which is a profile of text , as a d - dimensional unit vector .
10 // Component i of the vector indicates how many k - grams in the text hash to i .
11 public Sketch ( String text , int k , int d ) {
12 double [] freq = new double [ d ];
13 for ( int i = 0; i < text . length () - k + 1; i ++) {
14 String kgram = text . substring (i , i + k );
15 int hash = kgram . hashCode ();
16 freq [ Math . abs ( hash % d )]++;
17 }
18 Vector vector = new Vector ( freq );
19 sketch = vector . direction ();
20 }
21
22 // Returns the similarity measure between this and the other sketch , as a number between 0
23 // and 1. The value 0 indicates that the sketches are dissimilar , and 1 indicates that they are
24 // similar .
25 public double similarTo ( Sketch other ) {
26 return sketch . dot ( other . sketch );
27 }
28
29 // Returns a string re present ation of this sketch .
30 public String toString () {
31 return sketch . toString ();
32 }
33
34 // Unit tests the data type .
35 public static void main ( String [] args ) {
36 int k = Integer . parseInt ( args [0]);
37 int d = Integer . parseInt ( args [1]);
38 String text = StdIn . readAll ();
39 Sketch sketch = new Sketch ( text , k , d );
40 StdOut . println ( sketch );
41 }
42 }
& ~/workspace/ipj/programs
$ java Sketch 2 16 < ../ data / genome20 . txt
[0.0 , 0.0 , 0.0 , 0.6201736729460423 , 0.12403473458920847 , 0.0 , 0.37210420376762543 , 0.0 , 0.0 , 0.0 ,
0.12403473458920847 , 0.0 , 0.49613893835683387 , 0.37210420376762543 , 0.24806946917841693 , 0.0]
$ _
3.3.5 CompareDocuments.java
L CompareDocuments.java
1 // Accepts k ( int ) , d ( int ) , and path ( String ) as command - line arguments ; reads a document list
2 // from standard input ; computes d - dimensional profiles based on k - gram frequencies for all those
3 // documents under the path directory ; and writes to standard output a matrix of similarity
4 // measures between all pairs of documents .
5
6 import stdlib . In ;
7 import stdlib . StdIn ;
8 import stdlib . StdOut ;
9
10 public class C om pa re D o c u m e n t s {
11 // Entry point .
12 public static void main ( String [] args ) {
13 int k = Integer . parseInt ( args [0]);
51 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Co mp ar eD oc um en t s 5 10000 ../ data < ../ data / documents . txt
cons toms huck tale prej actg djia
cons 1.00 0.66 0.60 0.66 0.64 0.11 0.18
toms 0.66 1.00 0.93 0.88 0.88 0.14 0.24
huck 0.60 0.93 1.00 0.82 0.82 0.12 0.23
tale 0.66 0.88 0.82 1.00 0.85 0.13 0.22
prej 0.64 0.88 0.82 0.85 1.00 0.15 0.25
actg 0.11 0.14 0.12 0.13 0.15 1.00 0.11
djia 0.18 0.24 0.23 0.22 0.25 0.11 1.00
$ _
3.3.6 Counter.java
L Counter.java
1 // A comparable data type to represent a counter .
2
3 import java . util . Arrays ;
4
5 import stdlib . StdOut ;
6 import stdlib . StdRandom ;
7
8 public class Counter implements Comparable < Counter > {
9 private String id ; // counter name
10 private int count ; // current value
11
12 // Initializes a new counter with the given id .
13 public Counter ( String id ) {
14 this . id = id ;
15 count = 0;
16 }
17
18 // Increments this counter by 1.
19 public void increment () {
20 count ++;
21 }
22
23 // Returns the current value of this counter .
24 public int tally () {
25 return count ;
26 }
27
28 // Resets this counter to zero .
29 public void reset () {
30 count = 0;
31 }
32
33 // Returns true if this and the other counter have the same count , and false otherwise .
34 public boolean equals ( Object other ) {
35 if ( other == null ) {
36 return false ;
52 / 78
Introduction to Programming in Java
37 }
38 if ( other == this ) {
39 return true ;
40 }
41 if ( other . getClass () != this . getClass ()) {
42 return false ;
43 }
44 Counter a = this , b = ( Counter ) other ;
45 return a . count == b . count ;
46 }
47
48 // Returns a string re present ation of this counter .
49 public String toString () {
50 return count + " " + id ;
51 }
52
53 // Returns a comparison ( - ve , 0 , + ve ) of this and the other counter by count .
54 public int compareTo ( Counter other ) {
55 return Integer . compare ( this . count , other . count );
56 }
57
58 // Unit tests the data type .
59 public static void main ( String [] args ) {
60 int n = Integer . parseInt ( args [0]);
61 int trials = Integer . parseInt ( args [1]);
62 Counter [] counters = new Counter [ n ];
63 for ( int i = 0; i < n ; i ++) {
64 counters [ i ] = new Counter ( " counter " + i );
65 }
66 for ( int t = 0; t < trials ; t ++) {
67 counters [ StdRandom . uniform ( n )]. increment ();
68 }
69 Arrays . sort ( counters );
70 for ( Counter counter : counters ) {
71 StdOut . println ( counter );
72 }
73 }
74 }
& ~/workspace/ipj/programs
$ java Counter 6 10000
1634 counter 2
1641 counter 5
1652 counter 1
1657 counter 0
1692 counter 3
1724 counter 4
$ _
3.3.7 Country.java
L Country.java
1 // A comparable , immutable data type that represents a country by its name , capital , and population .
2
3 import stdlib . StdOut ;
4
5 import java . util . Arrays ;
6 import java . util . Comparator ;
7
8 public class Country implements Comparable < Country > {
9 private String name ; // name
10 private String capital ; // capital
11 private long population ; // population
12
13 // Constructs a country given its name , capital , and population .
14 public Country ( String name , String capital , long population ) {
15 this . name = name ;
16 this . capital = capital ;
17 this . population = population ;
18 }
19
20 // Returns a string re present ation of this country .
21 public String toString () {
22 return name + " ( " + capital + " ): " + population ;
23 }
24
53 / 78
Introduction to Programming in Java
54 / 78
Introduction to Programming in Java
105 }
106 }
& ~/workspace/ipj/programs
$ java Country
Unsorted :
United States ( Washington , D . C .): 329334246
Pakistan ( Islamabad ): 218719520
India ( New Delhi ): 1358989650
China ( Beijing ): 1401463880
Indonesia ( Jakarta ): 266911900
Sorted by name :
China ( Beijing ): 1401463880
India ( New Delhi ): 1358989650
Indonesia ( Jakarta ): 266911900
Pakistan ( Islamabad ): 218719520
United States ( Washington , D . C .): 329334246
Sorted by capital :
China ( Beijing ): 1401463880
Pakistan ( Islamabad ): 218719520
Indonesia ( Jakarta ): 266911900
India ( New Delhi ): 1358989650
United States ( Washington , D . C .): 329334246
Sorted by population :
Pakistan ( Islamabad ): 218719520
Indonesia ( Jakarta ): 266911900
United States ( Washington , D . C .): 329334246
India ( New Delhi ): 1358989650
China ( Beijing ): 1401463880
3.3.8 FibonacciSequence.java
L FibonacciSequence.java
1 // An iterable data type to iterate over the first n numbers from the Fibonacci sequence .
2
3 import java . util . Iterator ;
4
5 import stdlib . StdOut ;
6
7 public class F i bo n ac c i S e q u e n c e implements Iterable < Long > , Iterator < Long > {
8 private int n ; // length of the sequence
9 private long a ; // previous number in the sequence
10 private long b ; // current number in the sequence
11 private int count ; // count of the numbers iterated so far
12
13 // Constructs a F i b o n a c c i S e q u e n c e object given the length of the sequence .
14 public Fi b on a cc i S e q u e n c e ( int n ) {
15 this . n = n ;
16 }
17
18 // Returns an iterator that iterates over the numbers in the sequence .
19 public Iterator < Long > iterator () {
20 a = -1;
21 b = 1;
22 count = 0;
23 return this ;
24 }
25
26 // Returns true if there are more numbers in the sequence , and false otherwise .
27 public boolean hasNext () {
28 return count < n ;
29 }
30
31 // Returns the next number in the sequence .
32 public Long next () {
55 / 78
Introduction to Programming in Java
33 count ++;
34 long temp = a ;
35 a = b;
36 b += temp ;
37 return b ;
38 }
39
40 // Unit tests the data type .
41 public static void main ( String [] args ) {
42 int n = Integer . parseInt ( args [0]);
43 for ( long v : new F i b o n a c c i S e q u e n c e ( n )) {
44 StdOut . println ( v );
45 }
46 }
47 }
& ~/workspace/ipj/programs
$ java Fi b on a cc i Se q ue n c e 10
0
1
1
2
3
5
8
13
21
34
$ _
3.3.9 Words.java
L Words.java
1 // An iterable data type to iterate over the words in a sentence .
2
3 import java . util . Iterator ;
4
5 import stdlib . StdOut ;
6
7 public class Words implements Iterable < String > , Iterator < String > {
8 private String [] words ; // words in the sentence
9 private int current ; // index of the current word
10
11 // Constructs a Words object from the given sentence .
12 public Words ( String sentence ) {
13 words = sentence . split ( " \\ s + " );
14 }
15
16 // Returns an iterator to iterate over the words in a sentence .
17 public Iterator < String > iterator () {
18 current = 0;
19 return this ;
20 }
21
22 // Returns true if there are more words in the sentence , and false otherwise .
23 public boolean hasNext () {
24 return current < words . length ;
25 }
26
27 // Returns the next word in the sentence .
28 public String next () {
29 return words [ current ++];
30 }
31
32 // Unit tests the data type .
33 public static void main ( String [] args ) {
34 String sentence = args [0];
35 Words words = new Words ( sentence );
36 for ( String word : words ) {
37 StdOut . println ( word );
38 }
39 }
40 }
56 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Words " it was the best of times it was the worst of times "
it
was
the
best
of
times
it
was
the
worst
of
times
$ _
3.3.10 ErrorHandling.java
L ErrorHandling.java
1 // Accepts x ( double ) as command - line argument ; and writes to standard output the square root of
2 // x , reporting an error if x is not specified , is not a double , or is negative .
3
4 import stdlib . StdOut ;
5
6 public class ErrorHandling {
7 // Entry point .
8 public static void main ( String [] args ) {
9 try {
10 double x = Double . parseDouble ( args [0]);
11 double result = sqrt ( x );
12 StdOut . println ( result );
13 } catch ( A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n e ) {
14 StdOut . println ( " x not specified " );
15 } catch ( N u m b e r F o r m a t E x c e p t i o n e ) {
16 StdOut . println ( " x must be a double " );
17 } catch ( I l l e g a l A r g u m e n t E x c e p t i o n e ) {
18 StdOut . println ( e . getMessage ());
19 } finally {
20 StdOut . println ( " Done ! " );
21 }
22 }
23
24 // Returns the square root of x . Throws I l l e g a l A r g u m e n t E x c e p t i o n if x is negative .
25 private static double sqrt ( double x ) {
26 if ( x < 0) {
27 throw new I l l e g a l A r g u m e n t E x c e p t i o n ( " x must be positive " );
28 }
29 return Math . sqrt ( x );
30 }
31 }
& ~/workspace/ipj/programs
$ java ErrorHandling
x not specified
Done !
$ java ErrorHandling two
x must be a double
Done !
$ java ErrorHandling -2
x must be positve
Done !
$ java ErrorHandling 2
1 . 4 1 4 2 1 3 5 62 3 7 3 09 5 1
Done !
$ _
57 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Body
$ _
58 / 78
Introduction to Programming in Java
3.4.2 Universe.java
L Universe.java
1 // A data type to represent a universe .
2
3 import stdlib . StdDraw ;
4 import stdlib . In ;
5 import stdlib . StdOut ;
6
7 public class Universe {
8 private Body [] bodies ; // array of n bodies
9
10 // Constructs an n - body universe from the given file containing the number ( n ) of bodies ,
11 // their initial positions and velocities , and their masses .
12 public Universe ( String filename ) {
13 In inStream = new In ( filename );
14 int n = inStream . readInt ();
15 double radius = inStream . readDouble ();
16 StdDraw . setXscale ( - radius , + radius );
17 StdDraw . setYscale ( - radius , + radius );
18 bodies = new Body [ n ];
19 for ( int i = 0; i < n ; i ++) {
20 double rx = inStream . readDouble ();
21 double ry = inStream . readDouble ();
22 double vx = inStream . readDouble ();
23 double vy = inStream . readDouble ();
24 double mass = inStream . readDouble ();
25 double [] position = { rx , ry };
26 double [] velocity = { vx , vy };
27 Vector r = new Vector ( position );
28 Vector v = new Vector ( velocity );
29 bodies [ i ] = new Body (r , v , mass );
30 }
31 }
32
33 // Updates the state of this universe to what it would be after the given time period .
34 public void increaseTime ( double dt ) {
35 int n = bodies . length ;
36 Vector [] f = new Vector [ n ];
37 for ( int i = 0; i < n ; i ++) {
38 f [ i ] = new Vector ( new double [2]);
39 }
40 for ( int i = 0; i < n ; i ++) {
41 for ( int j = 0; j < n ; j ++) {
42 if ( i != j ) {
43 f [ i ] = f [ i ]. add ( bodies [ i ]. forceFrom ( bodies [ j ]));
44 }
45 }
46 }
47 for ( int i = 0; i < n ; i ++) {
48 bodies [ i ]. move ( f [ i ] , dt );
49 }
50 }
51
52 // Draws this universe to standard draw .
53 public void draw () {
59 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Universe ../ data /3 body . txt
$ _
3.4.3 NBody.java
L NBody.java
1 // Accepts filename ( String ) and dt ( double ) as command - line arguments ; uses the file with that
2 // name , specifying the number ( n ) of bodies , their initial positions and velocities , and their
3 // masses , to create an n - body universe ; and simulates the universe using dt as the time step .
4
5 import stdlib . StdDraw ;
6
7 public class NBody {
8 // Entry point .
9 public static void main ( String [] args ) {
10 String filename = args [0];
11 double dt = Double . parseDouble ( args [1]);
12 Universe universe = new Universe ( filename );
13 StdDraw . e n a b l e D o u b l e B u f f e r i n g ();
14 while ( true ) {
15 universe . increaseTime ( dt );
16 StdDraw . clear ();
17 universe . draw ();
18 StdDraw . show ();
19 StdDraw . pause (10);
60 / 78
Introduction to Programming in Java
20 }
21 }
22 }
& ~/workspace/ipj/programs
$ java NBody ../ data /3 body . txt 10000
$ _
& ~/workspace/ipj/programs
$ / usr / bin / time -f "% es " java ThreeSum ../ data /1 Kints . txt
70
0.29 s
61 / 78
Introduction to Programming in Java
$ / usr / bin / time -f "% es " java ThreeSum ../ data /2 Kints . txt
528
1.80 s
$ / usr / bin / time -f "% es " java ThreeSum ../ data /4 Kints . txt
4039
13.90 s
$ _
& ~/workspace/ipj/programs
$ / usr / bin / time -f "% es " java LinearSearch ../ data / tinyW . txt < ../ data / tinyT . txt
50
99
13
0.05 seconds
$ / usr / bin / time -f "% es " java LinearSearch ../ data / largeW . txt < ../ data / largeT . txt | tail -5
29798919
62 / 78
Introduction to Programming in Java
9505145
32449528
38862597
69830567
5955.22 seconds
$ _
4.2.2 BinarySearch.java
L BinarySearch.java
1 // A library that implements binary search .
2
3 import java . util . Arrays ;
4
5 import stdlib . In ;
6 import stdlib . StdIn ;
7 import stdlib . StdOut ;
8
9 public class BinarySearch {
10 // Returns the index of key in the sorted array a , or -1.
11 public static int indexOf ( Comparable [] a , Comparable key ) {
12 int lo = 0;
13 int hi = a . length - 1;
14 while ( lo <= hi ) {
15 int mid = lo + ( hi - lo ) / 2;
16 int cmp = key . compareTo ( a [ mid ]);
17 if ( cmp < 0) {
18 hi = mid - 1;
19 } else if ( cmp > 0) {
20 lo = mid + 1;
21 } else {
22 return mid ;
23 }
24 }
25 return -1;
26 }
27
28 // Returns the index of key in the sorted array a , or -1.
29 public static int indexOf ( int [] a , int key ) {
30 int lo = 0;
31 int hi = a . length - 1;
32 while ( lo <= hi ) {
33 int mid = lo + ( hi - lo ) / 2;
34 if ( key < a [ mid ]) {
35 hi = mid - 1;
36 } else if ( key > a [ mid ]) {
37 lo = mid + 1;
38 } else {
39 return mid ;
40 }
41 }
42 return -1;
43 }
44
45 // Returns the index of key in the sorted array a , or -1.
46 public static int indexOf ( double [] a , double key ) {
47 int lo = 0;
48 int hi = a . length - 1;
49 while ( lo <= hi ) {
50 int mid = lo + ( hi - lo ) / 2;
51 if ( key < a [ mid ]) {
52 hi = mid - 1;
53 } else if ( key > a [ mid ]) {
54 lo = mid + 1;
55 } else {
56 return mid ;
57 }
58 }
59 return -1;
60 }
61
62 // Unit tests the library .
63 public static void main ( String [] args ) {
64 In inStream = new In ( args [0]);
65 int [] whiteList = inStream . readAllInts ();
66 Arrays . sort ( whiteList );
67 while (! StdIn . isEmpty ()) {
63 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ / usr / bin / time -f "% es " java BinarySearch ../ data / tinyW . txt < ../ data / tinyT . txt
50
99
13
0.06 seconds
$ / usr / bin / time -f "% es " java BinarySearch ../ data / largeW . txt < ../ data / largeT . txt | tail -5
29798919
9505145
32449528
38862597
69830567
13.14 seconds
$ _
4.2.3 Zipf.java
L Zipf.java
1 // Accepts k ( int ) as command - line argument and words from standard input ; computes the number of
2 // times each word appears ; writes to standard output the k most frequent words in reverse order
3 // of their frequencies ; and draws using standard draw the corresponding histogram demonstrating
4 // Zipf ’s law ( ie , the power - law relationship between word frequencies and their ranks ).
5
6 import stdlib . StdIn ;
7 import stdlib . StdOut ;
8
9 public class Zipf {
10 // Entry point .
11 public static void main ( String [] args ) {
12 int k = Integer . parseInt ( args [0]);
13 String [] words = StdIn . readAl lString s ();
14 Merge . sort ( words );
15 Counter [] counters = new Counter [ words . length ];
16 int m = 0;
17 for ( int i = 0; i < words . length ; i ++) {
18 if ( i == 0 || ! words [ i ]. equals ( words [ i - 1])) {
19 counters [ m ] = new Counter ( words [ i ]);
20 m ++;
21 }
22 counters [ m - 1]. increment ();
23 }
24 Counter [] temp = new Counter [ m ];
25 for ( int i = 0; i < m ; i ++) {
26 temp [ i ] = counters [ i ];
27 }
28 counters = temp ;
29 Merge . sort ( counters );
30 Histogram histogram = new Histogram ( k );
31 for ( int i = 0; i < k ; i ++) {
32 Counter counter = counters [ m - i - 1];
33 StdOut . println ( counter );
34 for ( int j = 0; j < counter . tally (); j ++) {
35 histogram . addDataPoint ( i );
36 }
37 }
38 histogram . draw ();
39 }
40 }
& ~/workspace/ipj/programs
$ java Zipf 100 < ../ data / tomsawyer . txt
3452 the
2908 and
1758 a
1741 to
1539 of
...
64 / 78
Introduction to Programming in Java
89 other
88 under
87 know
87 ever
87 come
$ _
4.2.4 Insertion.java
L Insertion.java
1 // This library implements insertion sort .
2
3 import java . util . Comparator ;
4
5 import stdlib . StdIn ;
6 import stdlib . StdOut ;
7
8 public class Insertion {
9 // Sorts the specified array according to the natural ordering of its objects .
10 public static void sort ( Comparable [] a ) {
11 int n = a . length ;
12 for ( int i = 1; i < n ; i ++) {
13 for ( int j = i ; j > 0 && less ( a [ j ] , a [ j - 1]); j - -) {
14 exchange (a , j , j - 1);
15 }
16 }
17 }
18
19 // Sorts the specified array according to the order induced by the specified comparator .
20 public static void sort ( Object [] a , Comparator c ) {
21 int n = a . length ;
22 for ( int i = 1; i < n ; i ++) {
23 for ( int j = i ; j > 0 && less ( a [ j ] , a [ j - 1] , c ); j - -) {
24 exchange (a , j , j - 1);
25 }
26 }
27 }
28
29 // Sorts the specified array .
30 public static void sort ( int [] a ) {
31 int n = a . length ;
32 for ( int i = 1; i < n ; i ++) {
33 for ( int j = i ; j > 0 && a [ j ] < a [ j - 1]; j - -) {
34 int swap = a [ i ];
35 a [ i ] = a [ j ];
36 a [ j ] = swap ;
37 }
38 }
39 }
40
41 // Sorts the specified array .
42 public static void sort ( double [] a ) {
43 int n = a . length ;
44 for ( int i = 1; i < n ; i ++) {
45 for ( int j = i ; j > 0 && a [ j ] < a [ j - 1]; j - -) {
65 / 78
Introduction to Programming in Java
46 double swap = a [ i ];
47 a [ i ] = a [ j ];
48 a [ j ] = swap ;
49 }
50 }
51 }
52
53 // Returns true if the first object is less than the second according to their natural
54 // ordering , and false otherwise .
55 private static boolean less ( Comparable v , Comparable w ) {
56 return v . compareTo ( w ) < 0;
57 }
58
59 // Returns true if the first object is less than the second according to the order induced by
60 // the specified comparator , and false otherwise .
61 private static boolean less ( Object v , Object w , Comparator c ) {
62 return c . compare (v , w ) < 0;
63 }
64
65 // Exchanges two objects in the specified array .
66 private static void exchange ( Object [] a , int i , int j ) {
67 Object temp = a [ i ];
68 a [ i ] = a [ j ];
69 a [ j ] = temp ;
70 }
71
72 // Unit tests the library .
73 public static void main ( String [] args ) {
74 String [] a = StdIn . readA llString s ();
75 if ( args [0]. equals ( " -" )) {
76 sort (a , String . C A S E _ I N S E N S I T I V E _ O R D E R );
77 } else if ( args [0]. equals ( " + " )) {
78 sort ( a );
79 } else {
80 throw new I l l e g a l A r g u m e n t E x c e p t i o n ( " Illegal command - line argument " );
81 }
82 for ( String s : a ) {
83 StdOut . print ( s + " " );
84 }
85 StdOut . println ();
86 }
87 }
& ~/workspace/ipj/programs
$ java Insertion -
I n s e r t i o n S o r t
< ctrl -d >
e I i n n o o r r s S t t
$ java Insertion +
I n s e r t i o n S o r t
< ctrl -d >
I S e i n n o o r r s t t
$ _
4.2.5 Merge.java
L Merge.java
1 // This library implements merge sort .
2
3 import java . util . Comparator ;
4
5 import stdlib . StdIn ;
6 import stdlib . StdOut ;
7
8 public class Merge {
9 // Sorts the specified array according to the natural ordering of its objects .
10 public static void sort ( Comparable [] a ) {
11 Comparable [] aux = new Comparable [ a . length ];
12 sort (a , aux , 0 , a . length - 1);
13 }
14
15 // Sorts the specified array according to the order induced by the specified comparator .
16 public static void sort ( Object [] a , Comparator c ) {
17 Object [] aux = new Object [ a . length ];
18 sort (a , aux , 0 , a . length - 1 , c );
19 }
66 / 78
Introduction to Programming in Java
20
21 // Sorts the specified array .
22 public static void sort ( int [] a ) {
23 int [] aux = new int [ a . length ];
24 sort (a , aux , 0 , a . length - 1);
25 }
26
27 // Sorts the specified array .
28 public static void sort ( double [] a ) {
29 double [] aux = new double [ a . length ];
30 sort (a , aux , 0 , a . length - 1);
31 }
32
33 // Sorts the specified array from index lo to index hi according to the natural ordering of
34 // its objects .
35 private static void sort ( Comparable [] a , Comparable [] aux , int lo , int hi ) {
36 if ( hi <= lo ) {
37 return ;
38 }
39 int mid = lo + ( hi - lo ) / 2;
40 sort (a , aux , lo , mid );
41 sort (a , aux , mid + 1 , hi );
42 merge (a , aux , lo , mid , hi );
43 }
44
45 // Sorts the specified array from index lo to index hi according to the order induced by the
46 // specified comparator .
47 private static void sort ( Object [] a , Object [] aux , int lo , int hi , Comparator c ) {
48 if ( hi <= lo ) {
49 return ;
50 }
51 int mid = lo + ( hi - lo ) / 2;
52 sort (a , aux , lo , mid , c );
53 sort (a , aux , mid + 1 , hi , c );
54 merge (a , aux , lo , mid , hi , c );
55 }
56
57 // Sorts a [ lo , ... , hi ].
58 private static void sort ( int [] a , int [] aux , int lo , int hi ) {
59 if ( hi <= lo ) {
60 return ;
61 }
62 int mid = lo + ( hi - lo ) / 2;
63 sort (a , aux , lo , mid );
64 sort (a , aux , mid + 1 , hi );
65 merge (a , aux , lo , mid , hi );
66 }
67
68 // Sorts a [ lo , ... , hi ].
69 private static void sort ( double [] a , double [] aux , int lo , int hi ) {
70 if ( hi <= lo ) {
71 return ;
72 }
73 int mid = lo + ( hi - lo ) / 2;
74 sort (a , aux , lo , mid );
75 sort (a , aux , mid + 1 , hi );
76 merge (a , aux , lo , mid , hi );
77 }
78
79 // Merges the two halves ( index lo to index mid and index mid + 1 to index hi ) in the
80 // specified array according to the natural ordering of its objects .
81 private static void merge ( Comparable [] a , Comparable [] aux , int lo , int mid , int hi ) {
82 for ( int k = lo ; k <= hi ; k ++) {
83 aux [ k ] = a [ k ];
84 }
85 int i = lo , j = mid + 1;
86 for ( int k = lo ; k <= hi ; k ++) {
87 if ( i > mid ) {
88 a [ k ] = aux [ j ++];
89 } else if ( j > hi ) {
90 a [ k ] = aux [ i ++];
91 } else if ( less ( aux [ j ] , aux [ i ])) {
92 a [ k ] = aux [ j ++];
93 } else {
94 a [ k ] = aux [ i ++];
95 }
96 }
97 }
98
99 // Merges the two halves ( index lo to index mid and index mid + 1 to index hi ) in the
67 / 78
Introduction to Programming in Java
68 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Merge -
M e r g e S o r t
< ctrl -d >
e e g M o r r S t
$ java Merge +
M e r g e S o r t
< ctrl -d >
M S e e g o r r t
$ _
& ~/workspace/ipj/programs
$ java Reverse
b o l t o n
n o t l o b
$ _
4.3.2 ArrayStack.java
L ArrayStack.java
1 // An iterable data type to represent the Last - In - First - Out ( LIFO ) stack data structure .
2
3 import java . util . ArrayList ;
4 import java . util . Iterator ;
5 import java . util . N o S u c h E l e m e n t E x c e p t i o n ;
6
7 import stdlib . StdIn ;
8 import stdlib . StdOut ;
9
10 public class ArrayStack < Item > implements Iterable < Item > , Iterator < Item > {
11 private ArrayList < Item > a ; // items in the stack
12 private int current ; // index of current item
13
14 // Initializes an empty stack .
15 public ArrayStack () {
16 a = new ArrayList < Item >();
17 }
18
19 // Returns true if this stack is empty , and false otherwise .
69 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java ArrayStack < ../ data / tobe . txt
to be not that or be
2 items left in the stack
[ is , to ]
$ _
70 / 78
Introduction to Programming in Java
4.3.3 KthFromLast.java
L KthFromLast.java
1 // Accepts k ( int ) as command - line argument and a sequence of strings from standard input ; and
2 // writes the kth string from the end to standard output .
3
4 import stdlib . StdIn ;
5 import stdlib . StdOut ;
6
7 public class KthFromLast {
8 // Entry point .
9 public static void main ( String [] args ) {
10 int k = Integer . parseInt ( args [0]);
11 ArrayQueue < String > queue = new ArrayQueue < String >();
12 while (! StdIn . isEmpty ()) {
13 queue . enqueue ( StdIn . readString ());
14 }
15 int n = queue . size ();
16 for ( int i = 0; i < n - k ; i ++) {
17 queue . dequeue ();
18 }
19 StdOut . println ( queue . peek ());
20 }
21 }
& ~/workspace/ipj/programs
$ java KthFromLast 5
she sells sea shells on the sea shore
shells
$ _
4.3.4 ArrayQueue.java
L ArrayQueue.java
1 // An iterable data type to represent the First - In - First - Out ( FIFO ) queue data structure .
2
3 import java . util . ArrayList ;
4 import java . util . Iterator ;
5 import java . util . N o S u c h E l e m e n t E x c e p t i o n ;
6
7 import stdlib . StdIn ;
8 import stdlib . StdOut ;
9
10 public class ArrayQueue < Item > implements Iterable < Item > , Iterator < Item > {
11 private ArrayList < Item > a ; // items in the queue
12 private int current ; // index of current item
13
14 // Initializes an empty queue .
15 public ArrayQueue () {
16 a = new ArrayList < Item >();
17 }
18
19 // Returns true if this queue is empty , and false otherwise .
20 public boolean isEmpty () {
21 return a . isEmpty ();
22 }
23
24 // Returns the number of items in this queue .
25 public int size () {
26 return a . size ();
27 }
28
29 // Adds item to the end of this queue .
30 public void enqueue ( Item item ) {
31 a . add ( item );
32 }
33
34 // Returns the item at the front of this queue .
35 public Item peek () {
36 if ( isEmpty ()) {
37 throw new N o S u c h E l e m e n t E x c e p t i o n ( " Queue is empty " );
38 }
39 return a . get (0);
40 }
71 / 78
Introduction to Programming in Java
41
42 // Removes and returns the item at the front of this queue .
43 public Item dequeue () {
44 if ( isEmpty ()) {
45 throw new N o S u c h E l e m e n t E x c e p t i o n ( " Queue is empty " );
46 }
47 return a . remove (0);
48 }
49
50 // Returns an iterator that iterates over the items in this queue .
51 public Iterator < Item > iterator () {
52 current = 0;
53 return this ;
54 }
55
56 // Returns true if there are more items to iterate , and false otherwise .
57 public boolean hasNext () {
58 return current < a . size ();
59 }
60
61 // Returns the next item in the iterator .
62 public Item next () {
63 return a . get ( current ++);
64 }
65
66 // Returns a string re present ation of this queue .
67 public String toString () {
68 StringBuilder sb = new StringBuilder ();
69 for ( Item item : this ) {
70 sb . append ( item );
71 sb . append ( " , " );
72 }
73 return a . size () > 0 ? " [ " + sb . substring (0 , sb . length () - 2) + " ] " : " [] " ;
74 }
75
76 // Unit tests the data type .
77 public static void main ( String [] args ) {
78 ArrayQueue < String > queue = new ArrayQueue < String >();
79 while (! StdIn . isEmpty ()) {
80 String item = StdIn . readString ();
81 if (! item . equals ( " -" )) {
82 queue . enqueue ( item );
83 } else if (! queue . isEmpty ()) {
84 StdOut . print ( queue . dequeue () + " " );
85 }
86 }
87 StdOut . println ();
88 StdOut . println ( queue . size () + " items left in the queue " );
89 StdOut . println ( queue );
90 }
91 }
& ~/workspace/ipj/programs
$ java ArrayQueue < ../ data / tobe . txt
to be or not to be
2 items left in the queue
[ that , is ]
$ _
4.3.5 FrequencyCounter.java
L FrequencyCounter.java
1 // Accepts minLen ( int ) as command - line argument , and words from standard input ; and for the words
2 // that have at least minLen characters , writes to standard output the total word count , the
3 // number of distinct words , and the most frequent word .
4
5 import stdlib . StdIn ;
6 import stdlib . StdOut ;
7
8 public class F re qu en c y C o u n t e r {
9 // Entry point .
10 public static void main ( String [] args ) {
11 int minLen = Integer . parseInt ( args [0]);
12 int distinct = 0 , words = 0;
13 SymbolTable < String , Integer > st = new SymbolTable < String , Integer >();
14 while (! StdIn . isEmpty ()) {
72 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java Fr eq ue nc yC ou nt e r 8 < ../ data / tale . txt
Word count : 13525
Distinct word count : 4371
Most frequent word : business (134 repetitions )
$ _
4.3.6 SymbolTable.java
L SymbolTable.java
1 // A data type to represent a symbol table of key - value pairs .
2
3 import java . util . HashMap ;
4
5 import stdlib . StdOut ;
6
7 public class SymbolTable < Key , Value > {
8 private HashMap < Key , Value > st ; // a dictionary of key - value pairs
9
10 // Constructs an empty symbol table .
11 public SymbolTable () {
12 st = new HashMap < >();
13 }
14
15 // Returns true if this symbol table is empty , and false otherwise .
16 public boolean isEmpty () {
17 return st . isEmpty ();
18 }
19
20 // Returns the number of key - value pairs in this symbol table .
21 public int size () {
22 return st . size ();
23 }
24
25 // Returns true if this symbol table contains key , and false otherwise .
26 public boolean contains ( Key key ) {
27 return st . containsKey ( key );
28 }
29
30 // Returns the value associated with key in this symbol table .
31 public Value get ( Key key ) {
32 return st . get ( key );
33 }
34
35 // Inserts a key - value pair into this symbol table .
36 public void put ( Key key , Value value ) {
37 st . put ( key , value );
38 }
39
40 // Returns the keys in this symbol table , as an iterable object .
73 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java SymbolTable
Siddhartha
Charles
Albert
Einstein found
Newton not found
Einstein : Albert
Darwin : Charles
Gautama : Siddhartha
Albert
Charles
Siddhartha
$ _
74 / 78
Introduction to Programming in Java
7
8 public class Graph {
9 private SymbolTable < String , HashSet < String > > adj ; // maps each vertex to its neighbors
10 private int e ; // number of edges in graph
11
12 // Constructs an empty graph .
13 public Graph () {
14 adj = new SymbolTable < String , HashSet < String > >();
15 e = 0;
16 }
17
18 // Constructs a graph from the given file using the specified delimiter .
19 public Graph ( String filename , String delimiter ) {
20 this ();
21 In inStream = new In ( filename );
22 while ( inStream . hasNextLine ()) {
23 String line = inStream . readLine ();
24 String [] names = line . split ( delimiter );
25 for ( int i = 1; i < names . length ; i ++) {
26 addEdge ( names [0] , names [ i ]);
27 }
28 }
29 }
30
31 // Adds an undirected edge between vertices v and w in this graph .
32 public void addEdge ( String v , String w ) {
33 if (! hasVertex ( v )) {
34 adj . put (v , new HashSet < String >());
35 }
36 if (! hasVertex ( w )) {
37 adj . put (w , new HashSet < String >());
38 }
39 if (! hasEdge (v , w )) {
40 adj . get ( v ). add ( w );
41 adj . get ( w ). add ( v );
42 e ++;
43 }
44 }
45
46 // Returns true if v is a vertex in this graph , and false otherwise .
47 public boolean hasVertex ( String v ) {
48 return adj . contains ( v );
49 }
50
51 // Returns true if v - w is an edge in this graph , and false otherwise .
52 public boolean hasEdge ( String v , String w ) {
53 return adj . get ( v ). contains ( w );
54 }
55
56 // Returns the number of vertices in this graph .
57 public int countV () {
58 return adj . size ();
59 }
60
61 // Returns the number of edges in this graph .
62 public int countE () {
63 return e ;
64 }
65
66 // Returns the degree of vertex v in this graph .
67 public int degree ( String v ) {
68 return adj . get ( v ). size ();
69 }
70
71 // Returns the vertices adjacent to vertex v in this graph , as an iterable object .
72 public Iterable < String > vertices () {
73 return adj . keys ();
74 }
75
76 // Returns all the vertices in this graph , as an iterable object .
77 public Iterable < String > adjacentTo ( String v ) {
78 return adj . get ( v );
79 }
80
81 // Returns a string re present ation of this graph .
82 public String toString () {
83 String s = " " ;
84 for ( String v : vertices ()) {
85 s += v + " : " ;
86 for ( String w : adjacentTo ( v )) {
75 / 78
Introduction to Programming in Java
87 s += w + " " ;
88 }
89 s += " \ n " ;
90 }
91 return s ;
92 }
93
94 // Unit tests the data type .
95 public static void main ( String [] args ) {
96 String filename = args [0];
97 String delimiter = args [1];
98 Graph graph = new Graph ( filename , delimiter );
99 StdOut . println ( graph );
100 }
101 }
& ~/workspace/ipj/programs
$ java Graph ../ data / routes . txt " "
LAX : PHX LAS
LAS : LAX DEN
DEN : ORD PHX LAS
JFK : ORD MCO ATL
HOU : ORD DFW ATL
PHX : ORD LAX DFW DEN
ATL : ORD MCO JFK HOU
DFW : ORD PHX HOU
ORD : PHX DFW ATL DEN JFK HOU
MCO : ATL JFK
$ _
4.4.2 PathFinder.java
L PathFinder.java
1 // A data type to represent shortest paths within an undirected symbol graph from a fixed source
2 // vertex .
3
4 import stdlib . StdOut ;
5
6 public class PathFinder {
7 private Graph graph ; // the graph
8 private String s ; // the source vertex
9 private SymbolTable < String , Integer > distTo ; // maps a vertex to its distance from source
10 private SymbolTable < String , String > edgeTo ; // maps a vertex to previous vertex on path
11
12 // Constructs a path finder given the graph and source vertex .
13 public PathFinder ( Graph graph , String s ) {
14 this . graph = graph ;
15 this . s = s ;
16 distTo = new SymbolTable < String , Integer >();
17 edgeTo = new SymbolTable < String , String >();
18 ArrayQueue < String > queue = new ArrayQueue < String >();
19 queue . enqueue ( s );
20 distTo . put (s , 0);
21 while (! queue . isEmpty ()) {
22 String v = queue . dequeue ();
23 for ( String w : graph . adjacentTo ( v )) {
24 if (! distTo . contains ( w )) {
25 queue . enqueue ( w );
26 distTo . put (w , 1 + distTo . get ( v ));
27 edgeTo . put (w , v );
28 }
29 }
30 }
31 }
32
33 // Returns the distance of vertex v from the source vertex .
34 public int distanceTo ( String v ) {
35 return distTo . get ( v );
36 }
37
38 // Returns true if there is a path to vertex v from the source vertex , and false otherwise .
39 public boolean hasPathTo ( String v ) {
40 return distTo . contains ( v );
41 }
42
43 // Returns the path to vertex v from the source vertex .
76 / 78
Introduction to Programming in Java
& ~/workspace/ipj/programs
$ java PathFinder ../ data / routes . txt " " JFK
JFK -> ORD : JFK ORD (1)
JFK -> PHX : JFK ORD PHX (2)
JFK -> LAX : JFK ORD PHX LAX (3)
JFK -> DFW : JFK ORD DFW (2)
JFK -> MCO : JFK MCO (1)
JFK -> ATL : JFK ATL (1)
JFK -> DEN : JFK ORD DEN (2)
JFK -> JFK : JFK (0)
JFK -> HOU : JFK ORD HOU (2)
JFK -> LAS : JFK ORD DEN LAS (3)
$ _
4.4.3 Separation.java
L Separation.java
1 // Accepts filename ( String ) , delimiter ( String ) , and s ( String ) as command - line arguments ; and
2 // query vertices from standard input ; constructs a graph using filename , delimiter , and s ; and
3 // for each query vertex , writes to standard output the shortest path between the source vertex s
4 // and the query vertex , and the distance between the two .
5
6 import stdlib . StdIn ;
7 import stdlib . StdOut ;
8
9 public class Separation {
10 // Entry point .
11 public static void main ( String [] args ) {
12 String filename = args [0];
13 String delimiter = args [1];
14 String s = args [2];
15 Graph graph = new Graph ( filename , delimiter );
16 PathFinder pf = new PathFinder ( graph , s );
17 while ( StdIn . hasNextLine ()) {
18 String t = StdIn . readLine ();
19 if ( pf . hasPathTo ( t )) {
20 int distance = pf . distanceTo ( t );
21 for ( String v : pf . pathTo ( t )) {
22 StdOut . println ( " " + v );
23 }
24 StdOut . println ( " distance : " + distance );
25 }
77 / 78
Introduction to Programming in Java
26 }
27 }
28 }
& ~/workspace/ipj/programs
$ java Separation ../ data / movies . txt "/" " Bacon , Kevin "
Kidman , Nicole
Bacon , Kevin
Footloose (1984)
Wiest , Dianne
Practical Magic (1998)
Kidman , Nicole
distance : 4
Hanks , Tom
Bacon , Kevin
Apollo 13 (1995)
Hanks , Tom
distance : 2
$ _
78 / 78