Nothing Special   »   [go: up one dir, main page]

Chapter 1 Programing

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 180

Chapter 1 programing

HelloWorld.java
Below is the syntax highlighted version of HelloWorld.java from 1.1 Hello World.

/*************************************************************************
* Compilation: javac HelloWorld.java
* Execution:
java HelloWorld
*
* Prints "Hello, World". By tradition, this is everyone's first program.
*
* % java HelloWorld
* Hello, World
*
* These 17 lines of text are comments. They are not part of the program;
* they serve to remind us about its properties. The first two lines tell
* us what to type to compile and test the program. The next line describes
* the purpose of the program. The next few lines give a sample execution
* of the program and the resulting output. We will always include such
* lines in our programs and encourage you to do the same.
*
*************************************************************************/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}

UseArgument.java

Below is the syntax highlighted version of UseArgument.java from 1.1 Hello World.

/*************************************************************************
* Compilation: javac UseArgument.java
* Execution:
java UseArgument yourname
*

* Prints "Hi, Bob. How are you?" where "Bob" is replaced by the
* command-line argument.
*
* % java UseArgument Bob
* Hi, Bob. How are you?
*
* % java UseArgument Alice
* Hi, Alice. How are you?
*
*************************************************************************/
public class UseArgument {
public static void main(String[] args) {
System.out.print("Hi, ");
System.out.print(args[0]);
System.out.println(". How are you?");
}
}

TenHelloWorlds.java
Below is the syntax highlighted version of TenHelloWorlds.java from 1.1 Hello World.

/*************************************************************************
* Compilation: javac TenHelloWorlds.java
* Execution:
java TenHelloWorlds
*
* Prints "Hello, World" ten times. You'll learn about a more
* compact way to do this in Section 1.3 when we introduce loops.
*
* % java TenHelloWorlds
* Hello, World
* Hello, World
* Hello, World
* Hello, World
* Hello, World
* Hello, World
* Hello, World
* Hello, World
* Hello, World
* Hello, World
*
*************************************************************************/
public class TenHelloWorlds {
public static void main(String[] args) {

System.out.println("Hello,
System.out.println("Hello,
System.out.println("Hello,
System.out.println("Hello,
System.out.println("Hello,
System.out.println("Hello,
System.out.println("Hello,
System.out.println("Hello,
System.out.println("Hello,
System.out.println("Hello,

World");
World");
World");
World");
World");
World");
World");
World");
World");
World");

}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Dec 17 16:27:50 EST 2010.

Hi.java

Below is the syntax highlighted version of Hi.java from 1.1 Hello World.

/*************************************************************************
* Compilation: javac Hi.java
* Execution:
java Hi yourname
*
* Prints "Hi, Bob. How are you?" where "Bob" is replaced by the
* command-line parameter.
*
* % java Hi Bob
* Hi, Bob. How are you?
*
* % java Hi Alice
* Hi, Alice. How are you?
*
*************************************************************************/
public class Hi {
public static void main(String[] args) {
System.out.print("Hi, ");
System.out.print(args[0]);
System.out.println(". How are you?");
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Dec 17 16:27:50 EST 2010.

UseThree.java

Below is the syntax highlighted version of UseThree.java from 1.1 Hello World.

/*************************************************************************
* Compilation: javac UseThree.java
* Execution:
java UseThree name1 name2 name3
*
* Takes 3 command-line arguments and prints them in reverse order
* in a friendly greeting.
*
* % java UseThree Alice Bob Carol
* Hi, Carol, Bob, and Alice.
*
* % java UseThree Carol Bob Alice
* Hi, Alice, Bob, and Carol.
*
*************************************************************************/
public class UseThree {
public static void main(String[] args) {
System.out.print("Hi, ");
System.out.print(args[2]);
System.out.print(", ");
System.out.print(args[1]);
System.out.print(", and ");
System.out.print(args[0]);
System.out.println(".");
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Dec 17 16:27:50 EST 2010.

Initials.java

Below is the syntax highlighted version of Initials.java from 1.1 Hello World.

/*************************************************************************
* Compilation: javac Initials.java
* Execution:
java Initials
*
* Prints the initials K D W.
*
*************************************************************************/
public class Initials {
public static void main(String[] args) {
System.out.println("**
***
**********
**");
System.out.println("**
***
**
**
** ");
System.out.println("**
***
**
**
**
** ");
System.out.println("** ***
**
**
**
**
");
System.out.println("*****
**
**
**
**
");
System.out.println("** ***
**
**
**
**
");
System.out.println("**
***
**
**
** **
");
System.out.println("**
***
**
**
***
");
System.out.println("**
***
**********
*
");
}

**

**

***

**

**

**

**

**

**

**

**

** **
***
*

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Dec 17 16:27:50 EST 2010.

1.2 Built-in Types of Data


Ruler.java

Below is the syntax highlighted version of Ruler.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac Ruler.java
* Execution:
java Ruler
*
* Prints the relative lengths of the subdivisions on a ruler.
*
* % java Ruler
* 1

* 1 2 1
* 1 2 1 3 1 2 1
* 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
* 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
*
*************************************************************************/
public class Ruler {
public static void main(String[]
String ruler1 = " 1 ";
String ruler2 = ruler1 + "2"
String ruler3 = ruler2 + "3"
String ruler4 = ruler3 + "4"
String ruler5 = ruler4 + "5"

args) {
+
+
+
+

ruler1;
ruler2;
ruler3;
ruler4;

System.out.println(ruler1);
System.out.println(ruler2);
System.out.println(ruler3);
System.out.println(ruler4);
System.out.println(ruler5);
}
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Tue Nov 15 14:27:50 EST 2011.

IntOps.java

Below is the syntax highlighted version of IntOps.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac IntOps.java
* Execution:
java IntOps a b
*
* Illustrates the integer operations a * b, a / b, and a % b.
*
* % java IntOps 1234 99
* 1234 + 99 = 1333
* 1234 * 99 = 122166
* 1234 / 99 = 12
* 1234 % 99 = 46
* 1234 = 12 * 99 + 46
*
* % java IntOps 10 -3
* 10 + -3 = 7
* 10 * -3 = -30
* 10 / -3 = -3
* 10 % -3 = 1
* 10 = -3 * -3 + 1

*
*************************************************************************/
public class IntOps {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
int prod = a * b;
int quot = a / b;
int rem = a % b;
System.out.println(a
System.out.println(a
System.out.println(a
System.out.println(a
System.out.println(a
}

+
+
+
+
+

"
"
"
"
"

+
*
/
%
=

"
"
"
"
"

+
+
+
+
+

b + " = " + sum);


b + " = " + prod);
b + " = " + quot);
b + " = " + rem);
quot + " * " + b + " + " + rem);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

DoubleOps.java

Below is the syntax highlighted version of DoubleOps.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac DoubleOps.java
* Execution:
java DoubleOps a b
*
* Illustrates the integer operations a + b, a * b, and a / b.
*
* % java DoubleOps 1234 99
* 1234.0 + 99.0 = 1333.0
* 1234.0 * 99.0 = 122166.0
* 1234.0 / 99.0 = 12.464646464646465
* 1234.0 % 99.0 = 46.0
*
* % java DoubleOps 10 -3
* 10.0 + -3.0 = 7.0
* 10.0 * -3.0 = -30.0
* 10.0 / -3.0 = -3.3333333333333335
* 10.0 % -3.0 = 1.0
*
* % java DoubleOps Infinity 3
* Infinity + 3.0 = Infinity
* Infinity * 3.0 = Infinity
* Infinity / 3.0 = Infinity

* Infinity % 3.0 = NaN


*
*************************************************************************/
public class DoubleOps {
public static void main(String[] args) {
double a = Double.parseDouble(args[0]);
double b = Double.parseDouble(args[1]);
double sum = a + b;
double prod = a * b;
double quot = a / b;
double rem = a % b;
System.out.println(a
System.out.println(a
System.out.println(a
System.out.println(a

+
+
+
+

"
"
"
"

+
*
/
%

"
"
"
"

+
+
+
+

b
b
b
b

+
+
+
+

"
"
"
"

=
=
=
=

"
"
"
"

+
+
+
+

sum);
prod);
quot);
rem);

System.out.println();
System.out.println("sin(pi/2) = " + Math.sin(Math.PI/2));
System.out.println("log(e)
= " + Math.log(Math.E));
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

Quadratic.java

Below is the syntax highlighted version of Quadratic.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac Quadratic.java
* Execution:
java Quadatic b c
*
* Given b and c, solves for the roots of x*x + b*x + c.
* Assumes both roots are real valued.
*
* % java Quadratic -3.0 2.0
* 2.0
* 1.0
*
* % java Quadratic -1.0 -1.0
* 1.618033988749895
* -0.6180339887498949
*
* Remark: 1.6180339... is the golden ratio.
*
* % java Quadratic 1.0 1.0

* NaN
* NaN
*
*
*************************************************************************/
public class Quadratic {
public static void main(String[] args) {
double b = Double.parseDouble(args[0]);
double c = Double.parseDouble(args[1]);
double discriminant = b*b - 4.0*c;
double sqroot = Math.sqrt(discriminant);
double root1 = (-b + sqroot) / 2.0;
double root2 = (-b - sqroot) / 2.0;
System.out.println(root1);
System.out.println(root2);
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

Trig.java

Below is the syntax highlighted version of Trig.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac Trig.java
* Execution:
java Trig angle
*
* Illustrates various trig operations. Reads in an angle (in degrees),
* converts to radians, and performs various trigonometric
* calculations.
*
* % java Trig
* sin(30.0) = 0.49999999999999994
* cos(30.0) = 0.8660254037844387
* tan(30.0) = 0.5773502691896257
* 0.49999999999999994 / 0.8660254037844387 = 0.5773502691896256
* 0.24999999999999994 + 0.7500000000000001 = 1.0
*
*************************************************************************/
public class Trig {
public static void main(String[] args) {
double degrees = Double.parseDouble(args[0]);
double radians = Math.toRadians(degrees);

double s = Math.sin(radians);
System.out.println("sin(" + degrees + ") = " + s);
double c = Math.cos(radians);
System.out.println("cos(" + degrees + ") = " + c);
double t = Math.tan(radians);
System.out.println("tan(" + degrees + ") = " + t);
System.out.println(s + " / " + c + " = " + s / c);

double r = s*s + c*c;


System.out.println(s*s + " + " + c*c + " = " + r);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

LeapYear.java

Below is the syntax highlighted version of LeapYear.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac LeapYear.java
* Execution:
java LeapYear N
*
* Prints true if N corresponds to a leap year, and false otherwise.
* Assumes N >= 1582, corresponding to a year in the Gregorian calendar.
*
* % java LeapYear 2004
* true
*
* % java LeapYear 1900
* false
*
* % java LeapYear 2000
* true
*
*************************************************************************/
public class LeapYear {
public static void main(String[] args) {
int year = Integer.parseInt(args[0]);
boolean isLeapYear;
// divisible by 4
isLeapYear = (year % 4 == 0);
// divisible by 4 and not 100

isLeapYear = isLeapYear && (year % 100 != 0);


// divisible by 4 and not 100 unless divisible by 400
isLeapYear = isLeapYear || (year % 400 == 0);
System.out.println(isLeapYear);
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

RandomInt.java

Below is the syntax highlighted version of RandomInt.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac RandomInt.java
* Execution:
java RandomInt N
*
* Prints a pseudo-random integer between 0 and N-1.
* Illustrate an explicit type conversion (cast) from double to int.
*
* % java RandomInt 6
* Your random integer is: 5
*
* % java RandomInt 6
* Your random integer is: 0
*
* % java RandomInt 1000
* Your random integer is: 129
*
* % java RandomInt 1000
* Your random integer is: 333
*
*************************************************************************/
public class RandomInt {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// a pseudo-random real between 0.0 and 1.0
double r = Math.random();
// a pseudo-random integer between 0 and N-1
int n = (int) (r * N);
}
}

System.out.println("Your random integer is: " + n);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

Appendix A: Operator Precedence in Java

Java has well-defined rules for specifying the order in which the operators in an expression are
evaluated when the expression has several operators. For example, multiplication and division
have a higher precedence than addition and subtraction. Precedence rules can be overridden by
explicit parentheses.

Precedence Order.
When two operators share an operand the operator with the higher precedence
goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is
treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.

Associativity.
When two operators with the same precedence the expression is evaluated
according to its associativity. For example x = y = z = 17 is treated as x = (y = (z
= 17)), leaving all three variables with the value 17, since the = operator has rightto-left associativity (and an assignment statement evaluates to the value on the
right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the
/ operator has left-to-right associativity.

Precedence and associativity of Java operators.


The table below shows all Java operators from highest to lowest precedence, along
with their associativity. Most programmers do not memorize them all, and even
those that do still use parentheses for clarity.

Operator

Description

Level

Associativity

[]
.
()
++
--

access array element


access object member
invoke a method
post-increment
post-decrement

left to right

++
-+
-

pre-increment
pre-decrement
unary plus
unary minus

right to left

!
~

logical NOT
bitwise NOT

()
new

cast
object creation

right to left

*
/
%

multiplicative

left to right

+ +

additive
string concatenation

left to right

<< >>
>>>

shift

left to right

< <=
> >=
instanceof

relational
type comparison

left to right

==
!=

equality

left to right

&

bitwise AND

left to right

bitwise XOR

10

left to right

bitwise OR

11

left to right

&&

conditional AND

12

left to right

||

conditional OR

13

left to right

?:

conditional

14

right to left

assignment

15

right to left

=
*=
&=
<<=

+=
-=
/=
%=
^=
|=
>>= >>>=

Caveats.
There is no explicit operator precedence table in the Java Language Specification
and different tables on the Web and in textbooks disagree in some minor ways.

Order of evaluation.
In Java, the left operand is always evaluated before the right operand. Also applies
to function arguments.

Short circuiting. When using the conditional AND and OR operators (&& and ||), Java does not
evaluate the second operand unless it is necessary to resolve the result. Allows statements like if
(s != null && s.length() < 10) to work reliably. Programmers rarely use the non shortcircuiting versions (& and |) with boolean expressions.

Precedence order gone awry.


Sometimes the precedence order defined in a language do not conform with
mathematical norms. For example, in Microsoft Excel, -a^b is interpreted as (-a)^b
instead of -(a^b). So -1^2 is equal to 1 instead of -1, which is the values most
mathematicians would expect. Microsoft acknowledges this quirk as a "design
choice". One wonders whether the programmer was relying on the C precedence
order in which unary operators have higher precedence than binary operators. This
rule agrees with mathematical conventions for all C operators, but fails with the
addition of the exponentiation operator. Once the order was established in Microsoft
Excel 2.0, it could not easily be changed without breaking backward compatibility.
Exercises.
1. What is the result of the following code fragment?
int x = 5;
int y = 10;
int z = ++x * y--;

2. What is the result of the following code fragment? Explain.


System.out.println("1 + 2 = " + 1 + 2);
System.out.println("1 + 2 = " + (1 + 2));

Answer: 1 + 2 = 12 and 1 + 2 = 3, respectively. If either (or both) of the


operands of the + operator is a string, the other is automatically cast to a
string. String concatenation and addition have the same precedence. Since
they are left-associative, the operators are evaluated left-to-right. The
parentheses in the second statement ensures that the second + operator
performs addition instead of string concatenation.
3. Add parentheses to the following expression to make the order of evaluation
more clear.
year % 4 == 0 && year % 100 != 0 || year % 400 == 0

Answer: LeapYear.java shows a variety of equivalent expressions, including


the following reasonable alternative.
((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)

4. What does the following code fragment print?


System.out.println(1 + 2 + "abc");
System.out.println("abc" + 1 + 2);
Answer: 3abc and abc12, respectively. The +

operator is left associative, whether it is

string concatenation or arithmetic plus.

Last modified on April 10, 2013.


Copyright 20022012 Robert Sedgewick and Kevin Wayne. All rights reserved.
SumOfTwoDice.java

Below is the syntax highlighted version of SumOfTwoDice.java from 1.2 Built-in Types of
Data.

/*************************************************************************
* Compilation: javac SumOfTwoDice.java
* Execution:
java SumOfTwoDice
*
* Generate 2 integers between 1 and 6, and print their sum.
*
* % java SumOfTwoDice
* 5
*
* % java SumOfTwoDice
* 9
*
* % java SumOfTwoDice
* 3
*
* % java SumOfTwoDice
* 11
*
* % java SumOfTwoDice
* 8
*
* % java SumOfTwoDice
* 7

*
*************************************************************************/
public class SumOfTwoDice {
public static void main(String[] args) {
int SIDES = 6;
int a = 1 + (int) (Math.random() * SIDES);
int b = 1 + (int) (Math.random() * SIDES);
int sum = a + b;
System.out.println(sum);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

SpringSeason.java

Below is the syntax highlighted version of SpringSeason.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac SpringSeason.java
* Execution:
java day month
*
* Prints true if the given day and month fall between March 20 (inclusive)
* and June 20 (inclusive).
*
* % java SpringSeason 3 20
* true
*
* % java SpringSeason 6 20
* true
*
* % java SpringSeason 4 15
* true
*
* % java SpringSeason 9 11
* false
*
*************************************************************************/
public class SpringSeason {
public static void main(String[] args) {
int month = Integer.parseInt(args[0]);
int day
= Integer.parseInt(args[1]);
boolean isSpring = (month == 3 && day
|| (month == 4 && day
|| (month == 5 && day
|| (month == 6 && day
System.out.println(isSpring);

>= 20 && day <=


>= 1 && day <=
>= 1 && day <=
>= 1 && day <=

31)
30)
31)
20);

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Aug 5 06:49:33 EDT 2011.

WindChill.java

Below is the syntax highlighted version of WindChill.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac WindChill.java
* Execution:
java WindChill t v
*
* Given the temperature t (in Fahrenheit) and the wind speed v
* (in miles per hour), compute the wind chill w using the formula
* from the National Weather Service
*
*
w = 35.74 + 0.6215*t + (0.4275*t - 35.75) * v ^ 0.16
*
* Reference: http://www.nws.noaa.gov/om/windchill/index.shtml
*
*************************************************************************/
public class WindChill {
public static void main(String[] args) {
double t = Double.parseDouble(args[0]);
double v = Double.parseDouble(args[1]);
double w = 35.74 + 0.6215*t + (0.4275*t - 35.75) * Math.pow(v, 0.16);
System.out.println("Temperature = " + t);
System.out.println("Wind speed = " + v);
System.out.println("Wind chill = " + w);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

CartesianToPolar.java

Below is the syntax highlighted version of CartesianToPolar.java from 1.2 Built-in Types of
Data.

/*************************************************************************
* Compilation: javac CartesianToPolar.java
* Execution:
java CartesianToPolar x y
*
* Read in Cartesian coordinates (x, y) and print out polar coordinates
* (r, theta).
*
* % java CartesianToPolar 3.0 4.0
* r
= 5.0
* theta = 0.9272952180016122
*
*************************************************************************/
public class CartesianToPolar {
public static void main(String[] args) {
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
double r
= Math.sqrt(x*x + y*y);
double theta = Math.atan2(y, x);

System.out.println("r
= " + r);
System.out.println("theta = " + theta);

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Aug 5 06:50:31 EDT 2011.

DayOfWeek.java

Below is the syntax highlighted version of DayOfWeek.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac DayOfWeek.java
* Execution:
java DayOfWeek m d y
*
* Read in the month (m), day (d), and year (y) and print out what
* day of the week it falls on according to the Gregorian calendar.
* For M use 1 for January, 2 for February, and so forth. Outputs
* 0 for Sunday, 1 for Monday, and so forth.
*
*
y0 = y - (14 - m) / 12
*
x = y0 + y0/4 - y0/100 + y0/400
*
m0 = m + 12 * ((14 - m) / 12) - 2
*
d = (d + x + (31*m0)/12) mod 7
*
*
* % java DayOfWeek 8 2 1953
// August 2, 1953
* 0
// Sunday

*
* % java DayOfWeek 1 1 2000
// January 1, 2000
* 6
// Saturday
*
*************************************************************************/
public class DayOfWeek {
public static void main(String[] args) {
int m = Integer.parseInt(args[0]);
int d = Integer.parseInt(args[1]);
int y = Integer.parseInt(args[2]);
int
int
int
int

y0 = y - (14 - m) / 12;
x = y0 + y0/4 - y0/100 + y0/400;
m0 = m + 12 * ((14 - m) / 12) - 2;
d0 = (d + x + (31*m0)/12) % 7;

System.out.println(d0);
}
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Aug 5 06:46:18 EDT 2011.

Stats5.java

Below is the syntax highlighted version of Stats5.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac Stats5.java
* Execution:
java Stats5
*
* Generate and print 5 random values between 0.0 and 1.0, and print
* their average value, min value, and max value.
*
* % java Stats5
*
* 0.7203537279117841
* 0.09574435157738448
* 0.8979741693231866
* 0.11949032184355113
* 0.23425519545397544
* Average = 0.4135635532219763
* Min
= 0.09574435157738448
* Max
= 0.8979741693231866
*
* % java Stats5
* 0.25523821773554134
* 0.6577131932424987
* 0.14170223533941984

* 0.2653444869526621
* 0.895374957216799
* Average = 0.44307461809738424
* Min
= 0.14170223533941984
* Max
= 0.895374957216799
*
*************************************************************************/
public class Stats5 {
public static void main(String[] args) {
int N = 5;
double x1 = Math.random();
double x2 = Math.random();
double x3 = Math.random();
double x4 = Math.random();
double x5 = Math.random();
// print 5 values
System.out.println(x1);
System.out.println(x2);
System.out.println(x3);
System.out.println(x4);
System.out.println(x5);
// compute stats
double min
= Math.min(x1, Math.min(x2, Math.min(x3, Math.min(x4,
x5))));
x5))));

double max

= Math.max(x1, Math.max(x2, Math.max(x3, Math.max(x4,

double average = (x1 + x2 + x3 + x4 + x5) / N;


// print stats
System.out.println("Average = " + average);
System.out.println("Min
= " + min);
System.out.println("Max
= " + max);

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Aug 5 06:49:33 EDT 2011.

ThreeSort.java

Below is the syntax highlighted version of ThreeSort.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac ThreeSort.java
* Execution:
java ThreeSort a b c
*
* Read 3 integer values from the command line and print them

* in ascending order.
*
* % java ThreeSort 17 50 33
* 17
* 33
* 50
*
* % java ThreeSort 50 33 17
* 17
* 33
* 50
*
* % java ThreeSort 17 50 17
* 17
* 17
* 50
*
*************************************************************************/
public class ThreeSort {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
// compute
int min
int max
int median

stats
= Math.min(a, Math.min(b, c));
= Math.max(a, Math.max(b, c));
= a + b + c - min - max;

// print stats
System.out.println(min);
System.out.println(median);
System.out.println(max);
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Jan 27 04:32:10 EST 2012.

Dragon.java

Below is the syntax highlighted version of Dragon.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac Dragon.java
* Execution:
java Dragon
*
* Prints the instructions for drawing a dragon curve of orders 0
* through 5.

*
* % java Dragon
* F
* FLF
* FLFLFRF
* FLFLFRFLFLFRFRF
* FLFLFRFLFLFRFRFLFLFLFRFRFLFRFRF
* FLFLFRFLFLFRFRFLFLFLFRFRFLFRFRFLFLFLFRFLFLFRFRFRFLFLFRFRFLFRFRF
*
*************************************************************************/
public class Dragon {
public static void main(String[] args) {
String dragon0 = "F";
String nogard0 = "F";
String dragon1 = dragon0 + "L" + nogard0;
String nogard1 = dragon0 + "R" + nogard0;
String dragon2 = dragon1 + "L" + nogard1;
String nogard2 = dragon1 + "R" + nogard1;
String dragon3 = dragon2 + "L" + nogard2;
String nogard3 = dragon2 + "R" + nogard2;
String dragon4 = dragon3 + "L" + nogard3;
String nogard4 = dragon3 + "R" + nogard3;
String dragon5 = dragon4 + "L" + nogard4;

System.out.println(dragon0);
System.out.println(dragon1);
System.out.println(dragon2);
System.out.println(dragon3);
System.out.println(dragon4);
System.out.println(dragon5);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

Distance.java

Below is the syntax highlighted version of Distance.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac Distance.java
* Execution:
java Distance x y
*
* Print the distance from (x, y) to the origin, where x and y
* are integers.
*
* % java Distance 3 4
* distance from (3, 4) to (0, 0) = 5.0

*
* % java Distance 5 12
* distance from (5, 12) to (0, 0) = 13.0
*
* % java Distance 2 1
* distance from (2, 1) to (0, 0) = 2.23606797749979
*
*************************************************************************/
public class Distance {
public static void main(String[] args) {
// parse x- and y-coordinates from command-line arguments
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
// compute distance to (0, 0)
double dist = Math.sqrt(x*x + y*y);
// output distance
System.out.println("distance from (" + x + ", " + y + ") to (0, 0) = "

+ dist);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

Swap.java

Below is the syntax highlighted version of Swap.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac Swap.java
* Execution:
java Swap a b
*
* Read in two integer command-line arguments a and b and
* swap their values using the swapping idiom described on p. 17.
* After each assignment statement, use System.out.println() to
* print out a trace of the variables.
*
* % java Swap 11 99
* a = 11, b = 99, c = 0
* a = 11, b = 99, c = 11
* a = 99, b = 99, c = 11
* a = 99, b = 11, c = 11
*
*************************************************************************/
public class Swap {
public static void main(String[] args) {

int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = 0;

System.out.println("a
c = a;
System.out.println("a
a = b;
System.out.println("a
b = c;
System.out.println("a

= " + a + ", b = " + b + ", c = " + c);


= " + a + ", b = " + b + ", c = " + c);
= " + a + ", b = " + b + ", c = " + c);
= " + a + ", b = " + b + ", c = " + c);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

Divisibility.java

Below is the syntax highlighted version of Divisibility.java from 1.2 Built-in Types of Data.

Divisibility.java

Below is the syntax highlighted version of Divisibility.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac Divisibility.java
* Execution:
java Divisibility X Y
*
* Reads in two command line inputs X and Y and prints "true" if both
* are divisible by 7, and false otherwise.
*
* % java Divisibility 14 21
* true
*
* % java Divisibility 4 21
* false
*
* % java Divisibility 100 200
* false
*
* a % 7 is the remainder when you divide 7 into a. If the remainder
* is 0, then a is divisible by 7.
*

*************************************************************************/
public class Divisibility {
public static void main(String[] args) {
int X = Integer.parseInt(args[0]);
int Y = Integer.parseInt(args[1]);
boolean isDivisible = (X % 7 == 0) && (Y % 7 == 0);
System.out.println(isDivisible);
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Mar 23 06:39:40 EDT 2012.

CarLoan.java

Below is the syntax highlighted version of CarLoan.java from 1.2 Built-in Types of Data.

/*************************************************************************
* Compilation: javac CarLoan.java
* Execution:
java CarLoan P Y R
*
* Calculate the monthly payments if you take out a $P loan for
* Y years with annual interest rate R %, where interested is
* compounded monthly.
*
*
P r
*
payment = ----------------where n = 12 * Y, r = R / 12 / 100
*
1 - (1 + r)^(-n)
*
*
* % java CarLoan 20000 5 6
* Monthly payments = 386.6560305885655
* Total interest
= 3199.361835313932
*
*
* Bugs
* ---* Does not work if R = 0% interest. Easy to fix if you know about
* if-else statements.
*
*************************************************************************/

public class CarLoan {


public static void main(String[] args) {
double P = Double.parseDouble(args[0]);
double Y = Double.parseDouble(args[1]);
double R = Double.parseDouble(args[2]);
double r = R / 12 / 100;
double n = 12 * Y;

// monthly interest rate


// number of months

double payment = (P * r) / (1 - Math.pow(1+r, -n));


double interest = payment * n - P;

System.out.println("Monthly payments = " + payment);


System.out.println("Total interest
= " + interest);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Jan 31 13:10:13 EST 2011.

1.3 Conditionals and Loops


Flip.java

Below is the syntax highlighted version of Flip.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Flip.java
* Execution:
java Flip
*
* Simulate a fair coin flip and print out "Heads" or "Tails" accordingly.
*
* % java Flip
* Heads
*
* % java Flip
* Heads
*
* % java Flip
* Tails
*
*
*************************************************************************/
public class Flip {
public static void main(String[] args) {
// Math.random() returns a value between 0.0 and 1.0
// so it it heads or tails 50% of the time

if (Math.random() < 0.5) System.out.println("Heads");


else
System.out.println("Tails");
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

TenHellos.java

Below is the syntax highlighted version of TenHellos.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac TenHellos.java
* Execution:
java TenHellos
*
* Prints ith Hello for i = 1 to 10. Illlustrates using a while loop
* for a repetitive task.
*
* % java TenHellos
* 1st Hello
* 2nd Hello
* 3rd Hello
* 4th Hello
* 5th Hello
* 6th Hello
* 7th Hello
* 8th Hello
* 9th Hello
* 10th Hello
*
*************************************************************************/
public class TenHellos {
public static void main(String[] args) {
// print out special cases whose ordinal doesn't end in th
System.out.println("1st Hello");
System.out.println("2nd Hello");
System.out.println("3rd Hello");
// count from i = 4 to 10
int i = 4;
while (i <= 10) {
System.out.println(i + "th Hello");
i = i + 1;
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

PowersOfTwo.java

Below is the syntax highlighted version of PowersOfTwo.java from 1.3 Conditionals and
Loops.

/*************************************************************************
* Compilation: javac PowersOfTwo.java
* Execution:
java PowersOfTwo N
*
* This program takes a command-line argument N and prnts a table of
* the powers of 2 that are less than or equal to 2^N.
*
* % java PowersOfTwo 5
* 0 1
* 1 2
* 2 4
* 3 8
* 4 16
* 5 32
*
* % java PowersOfTwo 6
* 0 1
* 1 2
* 2 4
* 3 8
* 4 16
* 5 32
* 6 64
*
* Remarks
* -----------* Only works if 0 <= N < 31 since 2^31 overflows an int.
*
*************************************************************************/
public class PowersOfTwo {
public static void main(String[] args) {
// read in one command-line argument
int N = Integer.parseInt(args[0]);
int i = 0;
int powerOfTwo = 1;

// count from 0 to N-1


// the ith power of two

// repeat until i equals N


while (i <= N) {
System.out.println(i + " " + powerOfTwo);
of two

// print out the power

powerOfTwo = 2 * powerOfTwo;

next one
}

// double to get the

i = i + 1;

}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Harmonic.java

Below is the syntax highlighted version of Harmonic.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Harmonic.java
* Execution:
java Harmonic N
*
* Prints the Nth harmonic number: 1/1 + 1/2 + ... + 1/N.
*
* % java Harmonic 10
* 2.9289682539682538
*
* % java Harmonic 10000
* 9.787606036044348
*
*************************************************************************/
public class Harmonic {
public static void main(String[] args) {
// command-line argument
int N = Integer.parseInt(args[0]);
// compute
double sum
for (int i
sum +=
}

1/1 + 1/2 + 1/3 + ... + 1/N


= 0.0;
= 1; i <= N; i++) {
1.0 / i;

// print out Nth harmonic number


System.out.println(sum);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Sqrt.java

Below is the syntax highlighted version of Sqrt.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Sqrt.java
* Execution:
java Sqrt c
*
* Computes the square root of a nonnegative number c using
* Newton's method:
*
- initialize t = c
*
- replace t with the average of c/t and t
*
- repeat until desired accuracy reached
*
* % java Sqrt 2
* 1.414213562373095
*
* % java Sqrt 1000000
* 1000.0
*
* % java Sqrt 0.4
* 0.6324555320336759
*
* % java Sqrt 1048575
* 1023.9995117186336
*
* % java Sqrt 16664444
* 4082.2106756021303
*
* % java Sqrt 0
* 0.0
*
* % java Sqrt 1e-50
* 9.999999999999999E-26
*
*
* Remarks
* ---------*
- using Math.abs() is required if c < 1
*
*
* Known bugs
* ---------*
- goes into an infinite loop if the input is negative
*
*************************************************************************/
public class Sqrt {
public static void main(String[] args) {

// read in the command-line argument


double c = Double.parseDouble(args[0]);
double epsilon = 1e-15;
// relative error tolerance
double t = c;
// estimate of the square root of c
// repeatedly apply Newton update step until desired precision is

achieved

while (Math.abs(t - c/t) > epsilon*t) {


t = (c/t + t) / 2.0;
}
// print out the estimate of the square root of c
System.out.println(t);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Binary.java

Below is the syntax highlighted version of Binary.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Binary.java
* Execution:
java Binary n
*
* Prints out n in binary.
*
* % java Binary 5
* 101
*
* % java Binary 106
* 1101010
*
* % java Binary 0
* 0
*
* % java Binary 16
* 10000
*
* Limitations
* ----------* Does not handle negative integers.
*
* Remarks
* ------* could use Integer.toBinaryString(N) instead.

*
*************************************************************************/
public class Binary {
public static void main(String[] args) {
// read in the command-line argument
int n = Integer.parseInt(args[0]);
// set v to the largest power of two that is <= n
int v = 1;
while (v <= n/2) {
v = v * 2;
}
// check for presence of powers of 2 in n, from largest to smallest
while (v > 0) {
// v is not present in n
if (n < v) {
System.out.print(0);
}
// v is present in n, so remove v from n
else {
System.out.print(1);
n = n - v;
}

// next smallest power of 2


v = v / 2;

System.out.println();
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Gambler.java

Below is the syntax highlighted version of Gambler.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Gambler.java
* Execution:
java Gambler stake goal N
*
* Simulates a gambler who start with $stake and place fair $1 bets

* until she goes broke or reach $goal. Keeps track of the number of
* times she wins and the number of bets she makes. Run the experiment N
* times, averages the results, and prints them out.
*
* % java Gambler 50 250 1000
* Percent of games won = 19.0
* Avg # bets
= 9676.302
*
* % java Gambler 50 150 1000
* Percent of games won = 31.9
* Avg # bets
= 4912.13
*
* % java Gambler 50 100 1000
* Percent of games won = 49.6
* Avg # bets
= 2652.352
*
*************************************************************************/
public class Gambler {
public static
int stake
bankroll
int goal
bankroll
int T
perform

void main(String[] args) {


= Integer.parseInt(args[0]);

// gambler's stating

= Integer.parseInt(args[1]);

// gambler's desired

= Integer.parseInt(args[2]);

// number of trials to

int bets = 0;
int wins = 0;

// total number of bets made


// total number of games won

// repeat N times
for (int t = 0; t < T; t++) {
// do one gambler's ruin simulation
int cash = stake;
while (cash > 0 && cash < goal) {
bets++;
if (Math.random() < 0.5) cash++;
else
cash--;
}
if (cash == goal) wins++;
desired goal?
}

// win $1
// lose $1
// did gambler go achieve

// print results
System.out.println(wins + " wins of " + T);
System.out.println("Percent of games won = " + 100.0 * wins / T);
System.out.println("Avg # bets
= " + 1.0 * bets / T);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Factors.java

Below is the syntax highlighted version of Factors.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Factors.java
* Execution:
java Factors N
*
* Computes the prime factorization of N using brute force.
*
*
% java Factors 81
*
The prime factorization of 81 is: 3 3 3 3
*
*
% java Factors 168
*
The prime factorization of 168 is: 2 2 2 3 7
*
*
% java Factors 4444444444
*
The prime factorization of 4444444444 is: 2 2 11 41 271 9091
*
*
% java Factors 4444444444444463
*
The prime factorization of 4444444444444463 is: 4444444444444463
*
*
% java Factors 10000001400000049
*
The prime factorization of 10000001400000049 is: 100000007 100000007
*
*
% java Factors 1000000014000000049
*
The prime factorization of 1000000014000000049 is: 1000000007 1000000007
*
*
% java Factors 9201111169755555649
*
The prime factorization of 9201111169755555649 is: 3033333343 3033333343
*
*
Can use these for timing tests - biggest 3, 6, 9, 12, 15, and 18 digit
primes
*
% java Factors 997
*
% java Factors 999983
*
% java Factors 999999937
*
% java Factors 999999999989
*
% java Factors 999999999999989
*
% java Factors 999999999999999989
*
*
Remarks
*
------*
- Tests i*i <= N instead of i <= N for efficiency.
*
*
- The last two examples still take a few minutes.
*
*************************************************************************/
public class Factors {
public static void main(String[] args) {

// command-line argument
long n = Long.parseLong(args[0]);
System.out.print("The prime factorization of " + n + " is: ");
// for each potential factor i
for (long i = 2; i*i <= n; i++) {

// if i is a factor of N, repeatedly divide it out


while (n % i == 0) {
System.out.print(i + " ");
n = n / i;
}

// if biggest factor occurs only once, n > 1


if (n > 1) System.out.println(n);
else
System.out.println();
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Thu Feb 9 17:34:36 EST 2012.

Prime.java

Below is the syntax highlighted version of Prime.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Primes.java
* Execution:
java Primes N
*
* Determines whether or not N is prime.
*
*
% java Prime 81
*
81 is not prime
*
*
% java Prime 17
*
17 is prime
*
*
% java Prime 30864324691489
*
30864324691489 is not prime
*
*
*************************************************************************/
public class Prime {
public static void main(String[] args) {
long N = Long.parseLong(args[0]);
boolean isPrime = true;

if (N < 2) isPrime = false;


// try all possible factors i of N
// if if N has a factor, then it has one less than or equal to
sqrt(N),

// so for efficiency we only need to check i <= sqrt(N) or


equivalently i*i <= N
for (long i = 2; i*i <= N; i++) {
// if i divides evenly into N, N is not prime, so break out of
loop

if (N % i == 0) {
isPrime = false;
break;
}

// print out whether or not N is prime


if (isPrime) System.out.println(N + " is prime");
else
System.out.println(N + " is not prime");
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Thu Feb 2 14:54:15 EST 2012.

FivePerLine.java

Below is the syntax highlighted version of FivePerLine.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac FivePerLine.java
* Execution:
java FivePerLine
*
* Print the integers from 1000 to 2000, 5 per line.
*
* % java FivePerLine
*
*************************************************************************/
public class FivePerLine {
public static void main(String[] args) {
// print integers from 1000 to 2000, 5 per line
int start = 1000, end = 2000;
for (int i = start; i <= end; i++) {
System.out.print(i + " ");
if (i % 5 == 4) System.out.println();
}
System.out.println();

}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

RulerN.java

Below is the syntax highlighted version of RulerN.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac RulerN.java
* Execution:
java RulerN N
*
* Prints the relative lengths of the subdivisions on a ruler or
* order N.
*
* % java RulerN 3
*
1
*
1 2 1
*
1 2 1 3 1 2 1
*
* % java RulerN 5
*
1
*
1 2 1
*
1 2 1 3 1 2 1
*
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
*
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
*
* % java RulerN 100
* a lot of output, then
* Exception in thread "main" java.lang.OutOfMemoryError
*
*************************************************************************/
public class RulerN {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// ruler of order 0
String ruler = " ";
// repeat N times
for (int i = 1; i <= N; i++) {
order 0

// concatenate a ruler of order 0, the number i, and a ruler of


ruler = ruler + i + ruler;

// print out the final result


System.out.println(ruler);

}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

FunctionGrowth.java

Below is the syntax highlighted version of FunctionGrowth.java from 1.3 Conditionals and
Loops.

/*************************************************************************
* Compilation: javac FunctionGrowth.java
* Execution:
java FunctionGrowth
*
* Print out ln N, N, N log N, N^2, N^3 for N = 2, 4, 8, ..., 2048.
*
* % java FunctionGrowth
* log N
N
N log N N^2
N^3
* 0
2
1
4
8
* 1
4
5
16
64
* 2
8
16
64
512
* 2
16
44
256
4096
* 3
32
110
1024
32768
* 4
64
266
4096
262144
* 4
128
621
16384
2097152
* 5
256
1419
65536
16777216
* 6
512
3194
262144 134217728
* 6
1024
7097
1048576 1073741824
* 7
2048
15615
4194304 8589934592
*
*************************************************************************/
public class FunctionGrowth {
public static void main(String[] args) {
System.out.println("log N \tN \tN log N\tN^2 \tN^3");
for (long i = 2; i <= 2048; i *= 2) {
System.out.print((int) Math.log(i));
System.out.print('\t');
// tab character
System.out.print(i);
System.out.print('\t');
System.out.print((int) (i * Math.log(i)));
System.out.print('\t');
System.out.print(i * i);
System.out.print('\t');

System.out.print(i * i * i);
System.out.println();
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Ramanujan.java

Below is the syntax highlighted version of Ramanujan.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Ramanujan.java
* Execution:
java Ramanujan N
*
* Prints out any number between 1 and N that can be expressed as the
* sum of two cubes in two (or more) different ways.
*
* % java Ramanujan 1728
*
* % java Ramanujan 1729
* 1729 = 1^3 + 12^3 = 9^3 + 10^3
*
* % java Ramanujan 10000
* 1729 = 1^3 + 12^3 = 9^3 + 10^3
* 4104 = 2^3 + 16^3 = 9^3 + 15^3
*
* % java Ramanujan 100000
* 1729 = 1^3 + 12^3 = 9^3 + 10^3
* 4104 = 2^3 + 16^3 = 9^3 + 15^3
* 13832 = 2^3 + 24^3 = 18^3 + 20^3
* 39312 = 2^3 + 34^3 = 15^3 + 33^3
* 46683 = 3^3 + 36^3 = 27^3 + 30^3
* 32832 = 4^3 + 32^3 = 18^3 + 30^3
* 40033 = 9^3 + 34^3 = 16^3 + 33^3
* 20683 = 10^3 + 27^3 = 19^3 + 24^3
* 65728 = 12^3 + 40^3 = 31^3 + 33^3
* 64232 = 17^3 + 39^3 = 26^3 + 36^3
*
* % java Ramanujan 100000000 | sort -n
// sort results numerically in Unix
* 1729 = 1^3 + 12^3 = 9^3 + 10^3
* ...
* 87539319 = 167^3 + 436^3 = 228^3 + 423^3
* 87539319 = 167^3 + 436^3 = 255^3 + 414^3
* 87539319 = 228^3 + 423^3 = 255^3 + 414^3
* ...
*
* Bugs
* ----

* If a number can be expressed as a sum of cubes in more than two


* different ways, the program prints some duplicates.
*
*************************************************************************/
public class Ramanujan {
public static void main(String[] args) {
// read in one command-line argument
int N = Integer.parseInt(args[0]);
// for each a, b, c, d, check whether a^3 + b^3 = c^3 + d^3
for (int a = 1; a <= N; a++) {
int a3 = a*a*a;
if (a3 > N) break;
// start at a to avoid print out duplicate
for (int b = a; b <= N; b++) {
int b3 = b*b*b;
if (a3 + b3 > N) break;
// start at a + 1 to avoid printing out duplicates
for (int c = a + 1; c <= N; c++) {
int c3 = c*c*c;
if (c3 > a3 + b3) break;
// start at c to avoid printing out duplicates
for (int d = c; d <= N; d++) {
int d3 = d*d*d;
if (c3 + d3 > a3 + b3) break;
if (c3 + d3 == a3 + b3) {
System.out.print((a3+b3) + " = ");
System.out.print(a + "^3 + " + b + "^3 = ");
System.out.print(c + "^3 + " + d + "^3");
System.out.println();
}
}
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Dragon.java

Below is the syntax highlighted version of Dragon.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Dragon.java
* Execution:
java Dragon N
*
* Prints the instructions for drawing a dragon curve of orders N.
*
* % java Dragon 0
* F
*
* % java Dragon 1
* FLF
*
* % java Dragon 2
* FLFLFRF
*
* % java Dragon 3
* FLFLFRFLFLFRFRF
*
* % java Dragon 4
* FLFLFRFLFLFRFRFLFLFLFRFRFLFRFRF
*
* % java Dragon 5
* FLFLFRFLFLFRFRFLFLFLFRFRFLFRFRFLFLFLFRFLFLFRFRFRFLFLFRFRFLFRFRF
*
*************************************************************************/
public class Dragon {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
String dragon = "F";
String nogard = "F";
String temp;
for (int i = 1; i <= N; i++) {
temp = dragon;
dragon = dragon + "L" + nogard;
nogard = temp
+ "R" + nogard;
}
System.out.println(dragon);

// save away copy of dragon


// use old value of dragon

}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

ISBN.java

Below is the syntax highlighted version of ISBN.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac ISBN.java
* Execution:
java ISBN N
*
* Determines the check digit of an ISBN number given the first 9 digits.
*
* An ISBN number is legal if it consists of 10 digits and
* d_1 + 2*d_2 + 3*d_3 + ... + 10*d_10 is a multiple of 11.
* For example, 0-201-31452-5 is legal since
* 1*5 + 2*2 + 3*5 + 4*4 + 5*1 + 6*3 + 7*1 + 8*0 + 9*2 + 10*0 = 88
* and 88 is a multiple of 11.
*
* Sample execution:
*
*
% java ISBN 020131452
*
The full ISBN number is 201314525.
*
*************************************************************************/
public class ISBN {
public static void main(String[] args) {
// read in one command-line argument
int N = Integer.parseInt(args[0]);
// compute the weighted sum of the digits, from right to left
int sum = 0;
for (int i = 2; i <= 10; i++) {
int digit = N % 10;
// rightmost digit
sum = sum + i * digit;
N = N / 10;
}

// print out check digit, use X for 10


System.out.print("The full ISBN number is " + args[0]);
if
(sum % 11 == 1) System.out.println("X");
else if (sum % 11 == 0) System.out.println("0");
else
System.out.println(11 - (sum % 11));

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

ThueMorse.java

Below is the syntax highlighted version of ThueMorse.java from 1.3 Conditionals and Loops.

/*************************************************************************

* Compilation: javac ThueMorse.java


* Execution:
java ThueMorse N
*
* Prints the Thue-Morse sequence, which is defined as follows
*
*
Start with 0, and repeatedly flip all the bits and concatenate
*
it onto the original string.
*
* % java ThueMorse 0
* 0
*
* % java ThueMorse 1
* 01
*
* % java ThueMorse 2
* 0110
*
* % java ThueMorse 2
* 01101001
*
* % java ThueMorse 4
* 0110100110010110
*
* % java ThueMorse 5
* 01101001100101101001011001101001
*
*************************************************************************/
public class ThueMorse {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
String thue
= "0";
String morse = "1";
String t, m;
// temporary values
for (int i = 1; i <= N; i++) {
t = thue;
m = morse;
thue += m;
morse += t;
}
System.out.println(thue);

// save away values

}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Sin.java

Below is the syntax highlighted version of Sin.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Sin.java
* Execution:
java Sin x
*
* Prints out sin(x) using Taylor expansion.
*
*
sin x = x - x^3/3! + x^5/5! - x^7/7! + ...
*
* % java sin java Sin 0.523598775598299
* 0.5000000000000002
*
* Note: sin(pi/6) = sin(0.523598775598299...) = 1/2
*
* We use identity sin(x) = sin(x + 2 PI) to pre-process
* x to be between -2 PI and 2 PI. Yes, % works with doubles!
*
*************************************************************************/
public class Sin {
public static void main(String[] args) {
double x = Double.parseDouble(args[0]);
// convert x to an angle between -2 PI and 2 PI
x = x % (2 * Math.PI);
// compute the Taylor series approximation
double term = 1.0;
// ith term = x^i / i!
double sum = 0.0;
// sum of first i terms in taylor series
for (int i = 1; term != 0.0; i++) {
term *= (x / i);
if (i % 4 == 1) sum += term;
if (i % 4 == 3) sum -= term;
}
System.out.println(sum);
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

MonteHall.java

Below is the syntax highlighted version of MonteHall.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac MonteHall.java
* Execution:
java MonteHall N
*
* Plays the Monte Hall game N times with the switching strategy

* and reports the fraction of games won.


*
* Sample execution:
*
* % java MonteHall 10000000
* Fraction of games won = 0.666586
*
*
* Note: true winning probability = 2/3.
*
*************************************************************************/
public class MonteHall {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // # trials
int wins = 0;
// # times you win by switching
// repeat experiment N times
for (int i = 0; i < N; i++) {
// host hides prize behind 1 of 3 doors uniformly at random
int prize = (int) (3 * Math.random());
// contestant selects 1 of 3 doors uniformly at random
int choice = (int) (3 * Math.random());
// at random, host reveals an unchosen door not containing prize
int reveal;
do {
reveal = (int) (3 * Math.random());
} while ((reveal == choice) || (reveal == prize));
// hack to compute the remaining door which contestent switches to
int other = 0 + 1 + 2 - reveal - choice;
// switching leads to a win
if (other == prize) wins++;
}
// avoid integer division
System.out.println("Fraction of games won = " + 1.0 * wins / N);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

RollDie.java

Below is the syntax highlighted version of RollDie.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac RollDie.java
* Execution:
java RollDie
*
* Simulate the roll of a fair six-sided die
* and print the resulting number.
*
* % java RollDie
* 4
*
* % java RollDie
* 1
*
*************************************************************************/
public class RollDie {
public static void main(String[] args) {
int SIDES = 6;
// how many sides on the die?
// roll should be 1 through SIDES
int roll = (int) (Math.random() * SIDES) + 1;
// print result
System.out.println(roll);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

RollLoadedDie.java

Below is the syntax highlighted version of RollLoadedDie.java from 1.3 Conditionals and
Loops.

/*************************************************************************
* Compilation: javac RollLoadedDie.java
* Execution:
java RollLoadedDie
*
* Simulate the roll of a loaded six-sided die, where the values
* 1, 2, 3, 4, and 5 appear with probability 1/8 and the value 6
* appears with probablity 3/8, and print the resulting number.
*
* % java RollLoadedDie
* 4
*
* % java RollLoadedDie
* 6

*
*************************************************************************/
public class RollLoadedDie {
public static void main(String[] args) {
// double in the range [0.0, 1.0)
double r = Math.random();
// integer
int roll;
if
(r
else if (r
else if (r
else if (r
else if (r
else

in the range 1 to 6 with desired probabilities


<
<
<
<
<

1.0/8.0)
2.0/8.0)
3.0/8.0)
4.0/8.0)
5.0/8.0)

roll
roll
roll
roll
roll
roll

=
=
=
=
=
=

1;
2;
3;
4;
5;
6;

// print result
System.out.println(roll);
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Hurricane.java

Below is the syntax highlighted version of Hurricane.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Hurricane.java
* Execution:
java Hurricane N
*
* Reads in the wind speed (in miles per hour) and reports whether it is
* a hurricane, and if so, whether it is Class 1, 2, 3, 4 or 5 according
* to the Saffir-Simpson scale.
*
* Reference: http://www.marinewaypoints.com/marine/wind.shtml
*
* % java Hurricane 25
* Not a hurricane
*
* % java Hurricane 135
* Class 4 hurricane
*
*************************************************************************/

public class Hurricane {


public static void main(String[] args) {
int windSpeed = Integer.parseInt(args[0]);
if
else
else
else
else
else
}

if
if
if
if

(windSpeed
(windSpeed
(windSpeed
(windSpeed
(windSpeed

< 65) System.out.println("Not a hurricane");


< 96) System.out.println("Class 1 hurricane");
< 111) System.out.println("Class 2 hurricane");
< 131) System.out.println("Class 3 hurricane");
< 155) System.out.println("Class 4 hurricane");
System.out.println("Class 5 hurricane");

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Triangle.java

Below is the syntax highlighted version of Triangle.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Triangle.java
* Execution:
java Triangle N
*
* Prints out an N-by-N triangular pattern like the one below.
*
* % java Triangle
* * * * * * *
* . * * * * *
* . . * * * *
* . . . * * *
* . . . . * *
* . . . . . *
*
*************************************************************************/
public class Triangle {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// loop N times, one for each row
for (int i = 0; i < N; i++) {
// print j periods
for (int j = 0; j < i; j++)
System.out.print(". ");

// print N-i asterisks


for (int j = 0; j < N-i; j++)
System.out.print("* ");
// print a new line
System.out.println();
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Ex.java

Below is the syntax highlighted version of Ex.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Ex.java
* Execution:
java Ex N
*
* Prints out an X of radius N like the one below.
*
* % java Ex 3
* * . . . . . *
* . * . . . * .
* . . * . * . .
* . . . * . . .
* . . * . * . .
* . * . . . * .
* * . . . . . *
*
* % java Ex 5
* * . . . . . . . . . *
* . * . . . . . . . * .
* . . * . . . . . * . .
* . . . * . . . * . . .
* . . . . * . * . . . .
* . . . . . * . . . . .
* . . . . * . * . . . .
* . . . * . . . * . . .
* . . * . . . . . * . .
* . * . . . . . . . * .
* * . . . . . . . . . *
*
*************************************************************************/
public class Ex {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);

for (int i = -N; i <= N; i++) {


for (int j = -N; j <= N; j++) {
if ((i == -j) || (i == j)) System.out.print("* ");
else
System.out.print(". ");
}
System.out.println();
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

BowTie.java

Below is the syntax highlighted version of BowTie.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac BowTie.java
* Execution:
java BowTie N
*
* Prints out a bowtie of "radius" N like the one below.
*
* % java BowTie 3
* * . . . . . *
* * * . . . * *
* * * * . * * *
* * * * * * * *
* * * * . * * *
* * * . . . * *
* * . . . . . *
*
*************************************************************************/
public class BowTie {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);

}
}

for (int i = -N; i <= N; i++) {


for (int j = -N; j <= N; j++) {
if (i*i <= j*j) System.out.print("* ");
else
System.out.print(". ");
}
System.out.println();
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Diamond.java

Below is the syntax highlighted version of Diamond.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Diamond.java
* Execution:
java Diamond N
*
* Prints out a 2N+1-by-2N+1 diamond like the one below.
*
* % java Diamond 4
* . . . . * . . . .
* . . . * * * . . .
* . . * * * * * . .
* . * * * * * * * .
* * * * * * * * * *
* . * * * * * * * .
* . . * * * * * . .
* . . . * * * . . .
* . . . . * . . . .
*
*************************************************************************/
public class Diamond {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = -N; i <= N; i++) {
for (int j = -N; j <= N; j++) {
if (Math.abs(i) + Math.abs(j) <= N) System.out.print("* ");
else
System.out.print(". ");
}
System.out.println();
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Heart.java

Below is the syntax highlighted version of Heart.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Heart.java
* Execution:
java Heart N
*
* Prints out a heart.
*
* % java Heart 15
* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
* . . . . . . . . . . . . * * * * * * * . . . . . . . * * * * * *
* . . . . . . . . . . . .
* . . . . . . . . . . * * * * * * * * * * * . . . * * * * * * * * * *
* . . . . . . . . . .
* . . . . . . . . . * * * * * * * * * * * * * . * * * * * * * * * * * *
* . . . . . . . . .
* . . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* . . . . . . . .
* . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* . . . . . . .
* . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * . . . . . .
* . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * . . . . . .
* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * . . . . .
* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * . . . . .
* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * . . . . .
* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * . . . . .
* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * . . . . .
* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * . . . . .
* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * . . . . .
* . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * . . . . . .
* . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * . . . . . .
* . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* . . . . . . .

*
* .
*
* .
*
* .
*
* .
*
* .
*
* .
*
* .
*
* .
*
* .
*
* .
*
* .
*
* .
*
* .
*
* .
*
* .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. * * * * * * * * * * * * * * * * * * * * * * * * * * * *
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. * * * * * * * * * * * * * * * * * * * * * * * * * *
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. * * * * * * * * * * * * * * * * * * * * * * * *
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. * * * * * * * * * * * * * * * * * * * * * *
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. * * * * * * * * * * * * * * * * * * * *
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. * * * * * * * * * * * * * * * * * *
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. * * * * * * * * * * * * * * * *
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. * * * * * * * * * * * * * *
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. * * * * * * * * * * * *
.
.
.
.
.
.
.
.
.
.
.
.

. * * * * * * * * * *
.
.
.
.
.
.
.
.
.
.

. * * * * * * * *
.
.
.
.
.
.
.
.

. * * * * * *
.
.
.
.
.
.

. * * * *
. . * *
.
. . .
. .

* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
*
*************************************************************************/
public class Heart {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = -3*N/2; i <= N; i++) {
for (int j = -3*N/2; j <= 3*N/2; j++) {
// inside either diamond or two circles
if ( (Math.abs(i) + Math.abs(j) < N)
|| ((-N/2-i) * (-N/2-i) + ( N/2-j) * ( N/2-j) <= N*N/2)
|| ((-N/2-i) * (-N/2-i) + (-N/2-j) * (-N/2-j) <= N*N/2)
)
System.out.print("* ");
else
System.out.print(". ");
}
System.out.println();
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Circle.java

Below is the syntax highlighted version of Circle.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Circle.java
* Execution:
java Circle N
*
* Prints out a circle of radius N like the one below.
*
* % java Circle 5
* . . . . . * . . . . .
* . . * * * * * * * . .
* . * * * * * * * * * .
* . * * * * * * * * * .
* . * * * * * * * * * .
* * * * * * * * * * * *
* . * * * * * * * * * .
* . * * * * * * * * * .
* . * * * * * * * * * .
* . . * * * * * * * . .
* . . . . . * . . . . .
*
*************************************************************************/
public class Circle {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = -N; i <= N; i++) {
for (int j = -N; j <= N; j++) {
if (i*i + j*j <= N*N) System.out.print("* ");
else
System.out.print(". ");
}
System.out.println();
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Euler.java

Below is the syntax highlighted version of Euler.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Euler.java
* Execution:
java Euler N
*
* Tests whether there are any five positive integers that satisfy
* a^5 + b^5 + c^5 + d^5 = e^5. In 1769 Euler conjectured that no such
* solutions exists, but his conjecture was disproved in 1966 using
* a method like the one below.
*
* The program reads in a command line parameter N and prints out all
* solutions with a <= b <= c <= d <= e <= N. Restricting attention
* to solutions of this form only eliminates duplicates and makes
* the program faster since we have many fewer possibilities to try
* (675,993,780 vs. 75,937,500,000).
*
* For further efficiency, we use the break statement to avoid explicitly
* enumerating certain tuples (a, b, c, d, e), e.g., if a^5 + b^5
* is already greater than e^5, there is no need to fix specific
* values of c and d and compute a^5 + b^5 + c^5 + d^5. On my system,
* this decreased the running time from 3 minutes to 35 seconds.
*
* % java Euler 100
*
* % java Euler 150
*
27^5 + 84^5 + 110^5 + 133^5 = 144^5
// takes about 35 seconds
*
*
*************************************************************************/
public class Euler {
public static void main(String[] args) {
long N = Long.parseLong(args[0]);
long a5, b5, c5, d5, e5;
for (long e = 1; e <= N; e++) {
e5 = e*e*e*e*e;
// restrict search to a <= b <= c <= d <= e for efficiency
for (long a = 1; a <= N; a++) {
a5 = a*a*a*a*a;
if (a5 + a5 + a5 + a5 > e5) break;
for (long b = a; b <= N; b++) {
b5 = b*b*b*b*b;
if (a5 + b5 + b5 + b5 > e5) break;
for (long c = b; c <= N; c++) {
c5 = c*c*c*c*c;
if (a5 + b5 + c5 + c5 > e5) break;
for (long d = c; d <= N; d++) {
d5 = d*d*d*d*d;
if (a5 + b5 + c5 + d5 > e5) break;

if (a5 + b5 + c5 + d5 == e5)
System.out.println(a + "^5 + " + b + "^5
"^5 + " + d + "^5 = " + e + "^5");
}
}
}
}
}
}
}

+ " + c +

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Pepys.java

Below is the syntax highlighted version of Pepys.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Pepys.java
* Execution:
java Pepys N
*
* Which is more likely: at least one 1 in 6 rolls of a fair die, or
* at least two 1's in 12 rolls of a fair die?
*
* java Pepys 10000000
* 0.6651856
* 0.6186818
*
*************************************************************************/
public class Pepys {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// at least one 1 in 6 rolls
int cnt1 = 0;
for (int i = 0; i < N; i++) {
int >for (int j = 0; j < 6; j++)
if (6 * Math.random() < 1)
ones++;
if (ones >= 1) cnt1++;
}
// at least two 1's in 12 rolls
int cnt2 = 0;
for (int i = 0; i < N; i++) {
int >for (int j = 0; j < 12; j++)

if (6 * Math.random() < 1)
ones++;
if (ones >= 2) cnt2++;

System.out.println(1.0 * cnt1 / N);


System.out.println(1.0 * cnt2 / N);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Pal.java

Below is the syntax highlighted version of Pal.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac Pal.java
* Execution:
java Pal N
*
* % java Pal 1
* 11
*
* % java Pal 2
* 11211
*
* % java Pal 3
* 3112113
*
* % java Pal 4
* 311211343112113
*
* % java Pal 5
* 53112113431121135
*
*************************************************************************/
public class Pal {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
String s = "";
for (int i = 1; i <= N; i++) {
if (i % 2 == 0) s = s + i + s;
else
s = i + s + i;
}
System.out.println(s);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

SqrtBug.java

Below is the syntax highlighted version of SqrtBug.java from 1.3 Conditionals and Loops.

/*************************************************************************
* Compilation: javac SqrtBug.java
* Execution:
java Sqrt c
*
* Computes the square root of a nonnegative number c using
* Newton's method:
*
- initialize t = c
*
- replace t with the average of c/t and t
*
- repeat until desired accuracy reached [USING WRONG CONDITION]
*
* % java SqrtBug 2
* 1.414213562373095
*
* % java SqrtBug 1000000
* 1000.0
*
* % java SqrtBug 0.4
* 0.6324555320336759
*
* % java SqrtBug 1048575
* 1023.9995117186336
*
* % java SqrtBug 0
* 0.0
*
* % java SqrtBug 16664444
* [infinite loop]
*
* % java SqrtBug 1e-50
* 1.0E-50
* [wrong answer]
*
*
*
* Known bugs
* ---------*
- use the loop-continuation condition in Sqrt.java for reliable
*
results
*

*************************************************************************/
public class SqrtBug {
public static void main(String[] args) {
// read in the command-line argument
double c = Double.parseDouble(args[0]);
double t = c;
double EPSILON = 1e-15;

// estimate of the square root of c


// relative error tolerance

// repeatedly apply Newton update step until desired precision is


achieved
while (Math.abs(t*t - c) > EPSILON) {
t = (c/t + t) / 2.0;
}

// print out the estimate of the square root of c


System.out.println(t);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 08:58:48 EST 2011.

Arrays.java

Below is the syntax highlighted version of Arrays.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Arrays.java
* Execution:
java Arrays
*
* Typical array processing code.
*
* % java Arrays 5
* a[]
* ------------------* 0.04851944273872377
* 0.8311550808965679
* 0.5288965750549762
* 0.5053593215147596
* 0.6162362251917868
*
* a = [D@f62373
*
* max = 0.8311550808965679
* average = 0.5060333290793628
*

* b[]
* ------------------* 0.6162362251917868
* 0.5053593215147596
* 0.5288965750549762
* 0.8311550808965679
* 0.04851944273872377
*
* dot product of a[] and b[] = 1.1795943990991937
*
*************************************************************************/
public class Arrays {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initialize to random values between 0 and 1
double[] a = new double[N];
for (int i = 0; i < N; i++) {
a[i] = Math.random();
}
// print array values, one per line
System.out.println("a[]");
System.out.println("-------------------");
for (int i = 0; i < N; i++) {
System.out.println(a[i]);
}
System.out.println();
System.out.println("a = " + a);
System.out.println();
// find the maximum
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < N; i++) {
if (a[i] > max) max = a[i];
}
System.out.println("max = " + max);
// average
double sum = 0.0;
for (int i = 0; i < N; i++) {
sum += a[i];
}
System.out.println("average = " + sum / N);
// copy to
double[] b
for (int i
b[i] =
}

another array
= new double[N];
= 0; i < N; i++) {
a[i];

// reverse
for (int i
double
b[i] =

the order
= 0; i < N/2; i++) {
temp = b[i];
b[N-i-1];

b[N-i-1] = temp;

// print array values, one per line


System.out.println();
System.out.println("b[]");
System.out.println("-------------------");
for (int i = 0; i < N; i++) {
System.out.println(b[i]);
}
System.out.println();
// dot product of a[] and b[]
double dotProduct = 0.0;
for (int i = 0; i < N; i++) {
dotProduct += a[i] * b[i];
}
System.out.println("dot product of a[] and b[] = " + dotProduct);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

Deck.java

Below is the syntax highlighted version of Deck.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Deck.java
* Execution:
java Deck
*
* Deal 52 cards uniformly at random.
*
* % java Deck
* Ace of Clubs
* 8 of Diamonds
* 5 of Diamonds
* ...
* 8 of Hearts
*
*************************************************************************/
public class Deck {
public static void main(String[] args) {
String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };

String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Ace" };
// avoid hardwired constants
int SUITS = suit.length;
int RANKS = rank.length;
int N = SUITS * RANKS;
// initialize deck
String[] deck = new String[N];
for (int i = 0; i < RANKS; i++) {
for (int j = 0; j < SUITS; j++) {
deck[SUITS*i + j] = rank[i] + " of " + suit[j];
}
}
// shuffle
for (int i = 0; i < N; i++) {
int r = i + (int) (Math.random() * (N-i));
String t = deck[r];
deck[r] = deck[i];
deck[i] = t;
}
// print shuffled deck
for (int i = 0; i < N; i++) {
System.out.println(deck[i]);
}
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

Sample.java

Below is the syntax highlighted version of Sample.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Sample.java
* Execution:
java Sample M N
*
* This program takes two command-line arguments M and N and produces
* a random sample of M of the integers from 0 to N-1.
*
* % java Sample 6 49
* 10 20 0 46 40 6
*
* % java Sample 10 1000

* 656 488 298 534 811 97 813 156 424 109


*
*************************************************************************/
public class Sample {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);

// choose this many elements


// from 0, 1, ..., N-1

// create permutation 0, 1, ..., N-1


int[] perm = new int[N];
for (int i = 0; i < N; i++)
perm[i] = i;
// create random sample in perm[0], perm[1], ..., perm[M-1]
for (int i = 0; i < M; i++) {
// random integer between i and N-1
int r = i + (int) (Math.random() * (N-i));
// swap
int t =
perm[r]
perm[i]

elements at indices i and r


perm[r];
= perm[i];
= t;

}
// print results
for (int i = 0; i < M; i++)
System.out.print(perm[i] + " ");
System.out.println();
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

CouponCollector.java

Below is the syntax highlighted version of CouponCollector.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac CouponCollector.java
* Execution:
java CouponCollector N
*
* Given N distinct card types, how many random cards do you need
* do collect before you have (at least) one of each type?
* This program simulates this random process.
*
*
* % java CouponCollector 1000
* 6583

*
* % java CouponCollector 1000
* 6477
*
* % java CouponCollector 1000000
* 12782673
*
*************************************************************************/
public class CouponCollector {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// number of card types
boolean[] found = new boolean[N];
// found[i] = true if card i has
been collected
int cardcnt = 0;
// total number of cards
collected
int valcnt = 0;
// number of distinct cards

and N-1

// repeatedly choose a random card and check whether it's a new one
while (valcnt < N) {
int val = (int) (Math.random() * N);
// random card between 0

card

cardcnt++;

// we collected one more

if (!found[val]) valcnt++;
found[val] = true;

// it's a new card type


// update found[]

}
// print the total number of cards collected
System.out.println(cardcnt);
}

PrimeSieve.java

Below is the syntax highlighted version of PrimeSieve.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac PrimeSieve.java
* Execution:
java -Xmx1100m PrimeSieve N
*
* Computes the number of primes less than or equal to N using
* the Sieve of Eratosthenes.
*
* % java PrimeSieve 25
* The number of primes <= 25 is 9
*
* % java PrimeSieve 100
* The number of primes <= 100 is 25

*
* % java -Xmx100m PrimeSieve 100000000
* The number of primes <= 100000000 is 5761455
*
* % java PrimeSieve -Xmx1100m 1000000000
* The number of primes <= 1000000000 is 50847534
*
*
* The 110MB and 1100MB is the amount of memory you want to allocate
* to the program. If your computer has less, make this number smaller,
* but it may prevent you from solving the problem for very large
* values of N.
*
*
*
N
Primes <= N
* --------------------------------*
10
4
*
100
25
*
1,000
168
*
10,000
1,229
*
100,000
9,592
*
1,000,000
78,498
*
10,000,000
664,579
*
100,000,000
5,761,455
*
1,000,000,000
50,847,534
*
*************************************************************************/
public class PrimeSieve {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {

// if i is prime, then mark multiples of i as nonprime


// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}

// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]) primes++;
}
System.out.println("The number of primes <= " + N + " is " + primes);

HugeArray.java

Below is the syntax highlighted version of HugeArray.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac HugeArray.java
* Execution:
java HugeArray
*
* Attempts to create an array of size N^4 for N = 1000.
*
* This program compiles cleans.
* When N is 1000, it leads to the following error
*
*
java.lang.NegativeArraySizeException
*
* because 1000^4 overflows an int and results in a negative integer.
*
*
*
* When N is 200, it leads to the following error
*
*
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
*
*
*************************************************************************/
public class HugeArray {

public static void main(String[] args) {


int N = 1000;
int[] a = new int[N*N*N*N];
}

Deal.java

Below is the syntax highlighted version of Deal.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Deal.java

* Execution:
java Deal PLAYERS
*
* Deal 5-card hands at random to the given number of players.
*
* % java Deal 3
* 4 of Spades
* 9 of Spades
* Ace of Hearts
* 9 of Clubs
* 9 of Diamonds
*
* 6 of Spades
* 10 of Hearts
* Queen of Hearts
* 8 of Hearts
* King of Spades
*
* 7 of Hearts
* 8 of Diamonds
* Queen of Spades
* 3 of Spades
* 4 of Diamonds
*
*************************************************************************/
public class Deal {
public static void main(String[] args) {
int CARDS_PER_PLAYER = 5;
// number of players
int PLAYERS = Integer.parseInt(args[0]);
String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Ace" };
// avoid hardwired constants
int SUITS = suit.length;
int RANKS = rank.length;
int CARDS = SUITS * RANKS;
if (CARDS_PER_PLAYER * PLAYERS > CARDS) throw new
RuntimeException("Too many players");
// initialize deck
String[] deck = new String[CARDS];
for (int i = 0; i < RANKS; i++) {
for (int j = 0; j < SUITS; j++) {
deck[SUITS*i + j] = rank[i] + " of " + suit[j];
}
}
// shuffle
for (int i = 0; i < CARDS; i++) {
int r = i + (int) (Math.random() * (CARDS-i));

String t = deck[r];
deck[r] = deck[i];
deck[i] = t;

// print shuffled deck


for (int i = 0; i < PLAYERS * CARDS_PER_PLAYER; i++) {
System.out.println(deck[i]);
if (i % CARDS_PER_PLAYER == CARDS_PER_PLAYER - 1)
System.out.println();
}
}
}
.

Transpose.java

Below is the syntax highlighted version of Transpose.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Transpose.java
* Execution:
java Transpose 9
*
* Transpose an N-by-N matrix in-place, without creating a second
* 2D array.
*
* Submitted by Christian Rubio.
*
*************************************************************************/
public class Transpose {
public static void main(String[] args) {
// create N-by-N matrix
int N = Integer.parseInt(args[0]);
int[][] a = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
a[i][j] = N*i + j;
}
}
// print out initial matrix
System.out.println("Before");
System.out.println("------");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.printf("%4d", a[i][j]);
}

System.out.println();

// transpose in-place
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
int temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
// print out transposed matrix
System.out.println();
System.out.println("After");
System.out.println("------");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.printf("%4d", a[i][j]);
}
System.out.println();
}
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

SelfAvoidingWalk.java

Below is the syntax highlighted version of SelfAvoidingWalk.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac SelfAvoidingWalk.java
* Execution:
java SelfAvoidingWalk N T
*
* Generate T self-avoiding walks of length N.
* Report the fraction of time the random walk is non self-intersecting.
*
*************************************************************************/
public class SelfAvoidingWalk {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int T = Integer.parseInt(args[1]);
int deadEnds = 0;
end
// simulate T self-avoiding walks
for (int t = 0; t < T; t++) {

// lattice size
// number of trials
// trials resulting in a dead

boolean[][] a = new boolean[N][N];


int x = N/2, y = N/2;

// intersections visited
// current position

// repeatedly take a random step, unless you've already escaped


while (x > 0 && x < N-1 && y > 0 && y < N-1) {
// dead-end, so break out of loop
if (a[x-1][y] && a[x+1][y] && a[x][y-1] && a[x][y+1]) {
deadEnds++;
break;
}
// mark (x, y) as visited
a[x][y] = true;

// take a random step to unvisited neighbor


double r = Math.random();
if
(r < 0.25) { if (!a[x+1][y]) x++; }
else if (r < 0.50) { if (!a[x-1][y]) x--; }
else if (r < 0.75) { if (!a[x][y+1]) y++; }
else if (r < 1.00) { if (!a[x][y-1]) y--; }

}
}

System.out.println(100*deadEnds/T + "% dead ends");

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

InversePermutation.java

Below is the syntax highlighted version of InversePermutation.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac InversePermutation.java
* Execution:
java InversePermutation 5 0 2 3 1 4
*
* Read in a permutation from the command line and print out the inverse
* permutation.
*
*
% java InversePermutation 5 0 2 3 1 4
*
2 3 4 5 1 0
*
*************************************************************************/
public class InversePermutation {
public static void main(String[] args) {

int N = args.length;
// read in permutation
int[] a
= new int[N];
for (int i = 0; i < N; i++)
a[i] = Integer.parseInt(args[i]);
// check if valid
boolean[] exists = new boolean[N];
for (int i = 0; i < N; i++) {
if (a[i] < 0 || a[i] >= N || exists[a[i]])
throw new RuntimeException("Input is not a permutation.");
exists[a[i]] = true;
}
// invert
int[] ainv = new int[N];
for (int i = 0; i < N; i++)
ainv[a[i]] = i;

// print out
for (int i = 0; i < N; i++)
System.out.print(ainv[i] + " ");
System.out.println();

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

Hadamard.java

Below is the syntax highlighted version of Hadamard.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Hadamard.java
* Execution:
java Hadamard 16
*
* Prints the Hadamard matrix of order N. Assumes N is a power of 2.
*
* % java Hadamard 2
* * *
* * .
*
* % java Hadamard 4
* * * * *
* * . * .
* * * . .
* * . . *

*
*************************************************************************/
public class Hadamard {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
boolean[][] H = new boolean[N][N];
// initialize Hadamard matrix of order N
H[0][0] = true;
for (int n = 1; n < N; n += n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
H[i+n][j]
= H[i][j];
H[i][j+n]
= H[i][j];
H[i+n][j+n] = !H[i][j];
}
}
}
// print matrix
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (H[i][j]) System.out.print("* ");
else
System.out.print(". ");
}
System.out.println();
}
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

PrimeSieve.java

Below is the syntax highlighted version of PrimeSieve.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac PrimeSieve.java
* Execution:
java -Xmx1100m PrimeSieve N
*
* Computes the number of primes less than or equal to N using
* the Sieve of Eratosthenes.
*
* % java PrimeSieve 25
* The number of primes <= 25 is 9
*
* % java PrimeSieve 100

* The number of primes <= 100 is 25


*
* % java -Xmx100m PrimeSieve 100000000
* The number of primes <= 100000000 is 5761455
*
* % java PrimeSieve -Xmx1100m 1000000000
* The number of primes <= 1000000000 is 50847534
*
*
* The 110MB and 1100MB is the amount of memory you want to allocate
* to the program. If your computer has less, make this number smaller,
* but it may prevent you from solving the problem for very large
* values of N.
*
*
*
N
Primes <= N
* --------------------------------*
10
4
*
100
25
*
1,000
168
*
10,000
1,229
*
100,000
9,592
*
1,000,000
78,498
*
10,000,000
664,579
*
100,000,000
5,761,455
*
1,000,000,000
50,847,534
*
*************************************************************************/
public class PrimeSieve {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]) primes++;
}

System.out.println("The number of primes <= " + N + " is " + primes);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

Minesweeper.java

Below is the syntax highlighted version of Minesweeper.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Minesweeper.java
* Execution:
java Minesweeper M N p
*
* Creates an MxN minesweeper game where each cell is a bomb with
* probability p. Prints out the MxN game and the neighboring bomb
* counts.
*
* Sample execution:
*
*
% java Minesweeper 5 10 0.3
*
* . . . . . . . . *
*
. . . . . . * . . .
*
. . . . . . . . * *
*
. . . * * * . . * .
*
. . . * . . . . . .
*
*
* 1 0 0 0 1 1 1 1 *
*
1 1 0 0 0 1 * 2 3 3
*
0 0 1 2 3 3 2 3 * *
*
0 0 2 * * * 1 2 * 3
*
0 0 2 * 4 2 1 1 1 1
*
*
*************************************************************************/
public class Minesweeper {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
double p = Double.parseDouble(args[2]);
// game grid is [1..M][1..N], border is used to handle boundary cases
boolean[][] bombs = new boolean[M+2][N+2];
for (int i = 1; i <= M; i++)
for (int j = 1; j <= N; j++)
bombs[i][j] = (Math.random() < p);

// print game
for (int i = 1; i <= M; i++) {
for (int j = 1; j <= N; j++)
if (bombs[i][j]) System.out.print("* ");
else
System.out.print(". ");
System.out.println();
}
// sol[i][j] = # bombs adjacent to cell (i, j)
int[][] sol = new int[M+2][N+2];
for (int i = 1; i <= M; i++)
for (int j = 1; j <= N; j++)
// (ii, jj) indexes neighboring cells
for (int ii = i - 1; ii <= i + 1; ii++)
for (int jj = j - 1; jj <= j + 1; jj++)
if (bombs[ii][jj]) sol[i][j]++;
// print solution
System.out.println();
for (int i = 1; i <= M; i++) {
for (int j = 1; j <= N; j++)
if (bombs[i][j]) System.out.print("* ");
else
System.out.print(sol[i][j] + " ");
System.out.println();
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

RandomWalkers.java

Below is the syntax highlighted version of RandomWalkers.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac RandomWalkers.java
* Execution:
java RandomWalker N
*
* Simulates how long it takes N random walkers starting at the center
* of an N-by-N grid to visit every cell in the grid.
*
*************************************************************************/
public class RandomWalkers {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int[] x = new int[N];
// x positions
int[] y = new int[N];
// y positions

int cellsToVisit = N*N;


// cells left to visit
int steps = 0;
// number of steps taken
double r;
boolean[][] visited = new boolean[N][N]; // has the i-j been visited?
// start at center
for (int i = 0; i < N; i++) {
x[i] = N/2;
y[i] = N/2;
}
visited[N/2][N/2] = true;
cellsToVisit--;
// repeat until all cells have been visited
while (cellsToVisit > 0) {
steps++;
// move random walker i
for (int i = 0; i < N; i++) {
r = Math.random();
if
(r <= 0.25) { x[i]++;
else if (r <= 0.50) { x[i]--;
else if (r <= 0.75) { y[i]++;
else if (r <= 1.00) { y[i]--;
been visited

}
}
}
}

// check if (x[i], y[i]) is inside N-by-N boundary and has

if (x[i] < N && y[i] < N && x[i] >= 0 && y[i] >= 0 && !
visited[x[i]][y[i]]) {
cellsToVisit--;
visited[x[i]][y[i]] = true;
}
}
}
}

System.out.println(steps);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

Birthday.java

Below is the syntax highlighted version of Birthday.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Birthday.java
* Execution:
java Birthday D

*
* Computes the number of people (by simulation) that must enter a room
* until two of them share a birthday. Assumes birthdays a uniform
* and independent from 0 to D-1.
*
* % java Birthday 365
* 25
*
* % java Birthday 365
* 22
*
*************************************************************************/
public class Birthday {
public static void main(String[] args) {
int D = Integer.parseInt(args[0]);
int people = 0;

// number of days
// total number of people

// days[d] = true if someone born on day d; false otherwise


// auto-initialized to false
boolean[] days = new boolean[D];
while (true) {
people++;
int d = (int) (D * Math.random());
if (days[d]) break;
birthday, so break out of loop
days[d] = true;
}
}

// integer between 0 and D-1


// two people with the same
// update days[d]

System.out.println(people);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

HowMany.java

Below is the syntax highlighted version of HowMany.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac HowMany.java
* Execution:
java HowMany str1 str2 ... strN
*
* HowMany takes a variable number of command-line arguments
* and prints a message reporting how many there are.
*
*
% java HowMany

*
You entered 0 command-line arguments.
*
*
% java HowMany Alice Bob Carol
*
You entered 3 command-line arguments.
*
*
% java HowMany Alice
*
You entered 1 command-line argument.
*
*************************************************************************/
public class HowMany {
public static void main(String[] args) {
// number of command-line arguments
int N = args.length;

// output message
System.out.print("You entered " + N + " command-line argument");
if ( N == 1 ) System.out.println(".");
else
System.out.println("s.");

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

DiscreteDistribution.java

Below is the syntax highlighted version of DiscreteDistribution.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac DiscreteDistribution.java
* Execution:
java DiscreteDistribution freq0 freq1 freq2 ...
*
* Reads in an array of N frequency counts from the command line,
* and prints out i with probability proportional to the ith
* frequency count.
*
* // six equally likely events
* % java DiscreteDistribution 1 1 1 1 1 1
* 3
*
* % java DiscreteDistribution 1 1 1 1 1 1
* 0
*
* // six events, one 3x more likely than the others
* % java DiscreteDistribution 1 1 1 1 1 3
* 5
*
* % java DiscreteDistribution 1 1 1 1 1 3

* 2
*
* % java DiscreteDistribution 1 1 1 1 1 3
* 5
*
*************************************************************************/
public class DiscreteDistribution {
public static void main(String[] args) {
// read in frequency of occurrence of N values
int N = args.length;
int[] freq = new int[N];
for (int i = 0; i < N; i++) {
freq[i] = Integer.parseInt(args[i]);
}
// compute total count of all frequencies
int total = 0;
for (int i = 0; i < N; i++) {
total += freq[i];
}
// generate random integer with probability proportional to frequency
int r = (int) (total * Math.random());
// integer in [0, total)
int sum = 0;
int event = -1;
for (int i = 0; i < N && sum <= r; i++) {
sum += freq[i];
event = i;
}
}

System.out.println(event);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

Permutation.java

Below is the syntax highlighted version of Permutation.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Permutation.java
* Execution:
java Permutation N
*
* Prints a pseudorandom permution of the integers 0 through N.
*
*
% java Shuffle 6

*
5 0 2 3 1 4
*
. * . . . .
*
. . . . * .
*
. . * . . .
*
. . . * . .
*
. . . . . *
*
* . . . . .
*
*************************************************************************/
public class Permutation {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int[] a = new int[N];
// insert integers 0..N-1
for (int i = 0; i < N; i++)
a[i] = i;
// shuffle
for (int i = 0; i < N; i++) {
int r = (int) (Math.random() * (i+1));
int swap = a[r];
a[r] = a[i];
a[i] = swap;
}

// int between 0 and i

// print permutation
for (int i = 0; i < N; i++)
System.out.print(a[i] + " ");
System.out.println("");
// print checkerboard visualization
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (a[j] == i) System.out.print("* ");
else
System.out.print(". ");
}
System.out.println("");
}
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

LFSR.java

Below is the syntax highlighted version of LFSR.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac LFSR.java
* Execution:
java LFSR N
*
* Simulate a LFSR for N steps and print results.
*
* % java LFSR 40
* 0100110010000001100010001011101010111100
*
*************************************************************************/
public class LFSR {
public static void main(String[] args) {
// initial fill
boolean[] a = { false, true, false, false, false,
false, true, false, true, true, false
};
int T = Integer.parseInt(args[0]);
// number of steps
int N = a.length;
// length of register
int TAP = 8;
// tap position
// Simulate operation of shift register.
for (int t = 0; t < T; t++) {
// Simulate one shift-register step.
boolean next = (a[N-1] ^ a[TAP]); // Compute next bit.
for (int i = N-1; i > 0; i--)
a[i] = a[i-1];

// Shift one position.

a[0] = next;

// Put next bit on right end.

if (next) System.out.print("1");
else
System.out.print("0");
}
System.out.println();
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

KickBoxer.java

Below is the syntax highlighted version of KickBoxer.java from 1.4 Arrays.

/*************************************************************************

* Compilation: javac KickBoxer.java


* Execution:
java KickBoxer w
*
* Reads in the weight w of a Thai kickboxer, and prints out their
* kickboxing category (fly weight - super heavyweight).
*
* Reference: http://www.elitekickboxing.com/competitioninfo3.asp
*
* % java KickBoxer 144
* Welter Weight
*
* % java KickBoxer 300
* Super Heavy Weight
*
* % java KickBoxer 111
* Fly Weight
*
* % java KickBoxer 112
* Super Fly Weight
*
*************************************************************************/
public class KickBoxer {
public static void main(String[] args) {
int w = Integer.parseInt(args[0]);
int[] weights = { 112, 115, 118, 122, 126, 130, 135, 140, 147,
154, 160, 167, 174, 183, 189, 198, 209, 9999 };
String[] categories = { "Fly Weight",
"Super Fly Weight",
"Bantam Weight",
"Super Bantam Weight",
"Feather Weight",
"Super Feather Weight",
"Light Weight",
"Super Light Weight",
"Welter Weight",
"Super Welter Weight",
"Middle Weight",
"Super Middle Weight",
"Light Heavy Weight",
"Super Light Heavy Weight",
"Cruiser Weight",
"Super Cruiser Weight",
"Heavy Weight",
"Super Heavy Weight"
};

for (int i = 0; i < weights.length; i++) {


if (w < weights[i]) {
System.out.println(categories[i]);
break;
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

MagicSquare.java

Below is the syntax highlighted version of MagicSquare.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac MagicSquare.java
* Execution:
java MagicSquare N
*
* Generates a magic square of order N. A magic squares is an N-by-N
* matrix of the integers 1 to N^2, such that all row, column, and
* diagonal sums are equal.
*
* One way to generate a magic square when N is odd is to assign
* the integers 1 to N^2 in ascending order, starting at the
* bottom, middle cell. Repeatedly assign the next integer to the
* cell adjacent diagonally to the right and down. If this cell
* has already been assigned another integer, instead use the
* cell adjacently above. Use wrap-around to handle border cases.
*
*
* % java MagicSquare 3
*
4 9 2
*
3 5 7
*
8 1 6
*
* % java MagicSquare 5
* 11 18 25 2 9
* 10 12 19 21 3
*
4 6 13 20 22
* 23 5 7 14 16
* 17 24 1 8 15
*
* Limitations
* ----------*
- N must be odd
*
*************************************************************************/
public class MagicSquare {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (N % 2 == 0) throw new RuntimeException("N must be odd");
int[][] magic = new int[N][N];

int row = N-1;


int col = N/2;
magic[row][col] = 1;
for (int i = 2; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
// don't change col
}
magic[row][col] = i;
}
// print results
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (magic[i][j] < 10) System.out.print(" ");
alignment
if (magic[i][j] < 100) System.out.print(" ");
alignment
System.out.print(magic[i][j] + " ");
}
System.out.println();
}
}

// for
// for

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

ZipBarCoder.java

Below is the syntax highlighted version of ZipBarCoder.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac ZipBarCoder.java
* Execution:
java ZipBarCoder N
*
* Reads in a 5 digit zip code and prints out the postal barcode.
*
*************************************************************************/
public class ZipBarCoder {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int[] digits = new int[6];

int[][] code = { {
{
{
{
{
{
{
{
{
{

1,
0,
0,
0,
0,
0,
0,
1,
1,
1,

1,
0,
0,
0,
1,
1,
1,
0,
0,
0,

0,
0,
1,
1,
0,
0,
1,
0,
0,
1,

0,
1,
0,
1,
0,
1,
0,
0,
1,
0,

0
1
1
0
1
0
0
1
0
0

},
},
},
},
},
},
},
},
},
} };

// extract digits
for (int i = 1; i <= 5; i++) {
digits[i] = N % 10;
N /= 10;
}
// compute check digit
int checkdigit = 0;
for (int i = 1; i <= 5; i++)
checkdigit += digits[i];
digits[0] = checkdigit % 10;
// print barcode
System.out.println("*****");
for (int i = 5; i >= 0; i--)
for (int j = 0; j < 5; j++)
if (code[digits[i]][j] == 1) System.out.println("*****");
else
System.out.println("**");
System.out.println("*****");
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

PrimeGap.java

Below is the syntax highlighted version of PrimeGap.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac PrimeGap.java
* Execution:
java -Xmx900MB -Xms900MB PrimeGap N
*
* Find the longest consecutive sequence of integers between 2 and N
* with no primes.
*
* Sample execution:
*
*
% java -Xmx900MB -Xms900MB PrimeGap 100

*
There are no primes between 90 and 96
*
That is 7 consecutive integers
*
*
% java -Xmx900MB -Xms900MB PrimeGap 100000000
*
There are no primes between 47326694 and 47326912
*
That is 219 consecutive integers
*
*
*************************************************************************/
public class PrimeGap {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
boolean[] isprime = new boolean[N+1];
for (int i = 2; i <= N; i++)
isprime[i] = true;
// determine primes < N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
if (isprime[i]) {
for (int j = i; i*j <= N; j++)
isprime[i*j] = false;
}
}
// find longest consecutive sequence of integers with no primes
int gap = 0;
int bestgap = 0;
int right = 0;
for (int i = 2; i <= N; i++) {
if (isprime[i]) gap = 0;
else gap++;
if (gap > bestgap) { bestgap = gap; right = i; }
}
int left = right - bestgap + 1;
System.out.println("There are no primes between " + left + " and " +
right);
}

System.out.println("That is " + bestgap + " consecutive integers");

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

Goldbach.java

Below is the syntax highlighted version of Goldbach.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Goldbach.java
* Execution:
java -Xmx900MB -Xms900MB Goldbach N
*
* Computes all primes less than N and tries to express N as a sum
* of two primes. Goldbach's conjecture says that this is always
* possible if N is even and greater than 2. When N is odd, these
* are called prime pairs.
* Sample execution:
*
*
%java -Xmx900MB -Xms900MB Goldbach 10003292
*
10003292 = 349 + 10002943
*
*
%java -Xmx900MB -Xms900MB Goldbach 10000001
*
10000001 is not expressible as the sum of two primes
*
*
%java -Xmx900MB -Xms900MB Goldbach 10000021
*
10000021 = 2 + 10000019
*
*************************************************************************/
public class Goldbach {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
boolean[] isprime = new boolean[N];
for (int i = 2; i < N; i++)
isprime[i] = true;
// determine primes <
for (int i = 2; i * i
if (isprime[i]) {
for (int j = i;
isprime[i*j]
}
}

N using Sieve of Eratosthenes


< N; i++) {
i * j < N; j++)
= false;

// count primes
int primes = 0;
for (int i = 2; i < N; i++)
if (isprime[i]) primes++;
System.out.println("Done tabulating primes.");
// store primes in list
int[] list = new int[primes];
int n = 0;
for (int i = 0; i < N; i++)
if (isprime[i]) list[n++] = i;
// check if N can be expressed as sum of two primes
int left = 0, right = primes-1;
while (left <= right) {
if
(list[left] + list[right] == N) break;

else if (list[left] + list[right]


else right--;

< N) left++;

}
if (list[left] + list[right] == N)
System.out.println(N + " = " + list[left] + " + " + list[right]);
else
System.out.println(N + " not expressible as sum of two primes");

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

Spiral.java

Below is the syntax highlighted version of Spiral.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Spiral.java
* Execution:
java Spiral N
*
* % java Spiral 4
* java Spiral 4
* 1
* 2
* 3
* 4
* 8
* 12
* 16
* 15
* 14
* 13
* 9
* 5
* 6
* 7
* 11
* 10
*
*************************************************************************/
public class Spiral {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// create N-by-N array of integers 1 through N
int[][] a = new int[N][N];
for (int i = 0; i < N; i++)

for (int j = 0; j < N; j++)


a[i][j] = 1 + N*i + j;
// spiral
for (int i = N-1, j =
for (int k = j;
for (int k = j;
for (int k = i;
for (int k = i;

0; i >
k < i;
k < i;
k > j;
k > j;

0; i--, j++) {
k++) System.out.println(a[j][k]);
k++) System.out.println(a[k][i]);
k--) System.out.println(a[i][k]);
k--) System.out.println(a[k][j]);

// special case for middle element if N is odd


if (N % 2 == 1) System.out.println(a[(N-1)/2][(N-1)/2]);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

Euler.java

Below is the syntax highlighted version of Euler.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Euler.java
* Execution:
java Euler N
*
* Tests whether there are any five positive integers that satisfy
* a^5 + b^5 + c^5 + d^5 = e^5. In 1769 Euler conjectured that no such
* solutions exists, but his conjecture was disproved in 1966 using
* a computational approach like the one we take here.
*
* The program reads in a command line parameter N and prints out all
* solutions with a <= b <= c <= d <= e <= N. To speed things up by
* roughly a factor of 3 on my system, we precompute an array of
* fifth powers.
*
* % java Euler 100
*
* % java Euler 150
*
27^5 + 84^5 + 110^5 + 133^5 = 144^5
// takes about 20 seconds
*
*
*************************************************************************/
public class Euler {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);

// precompute i^5 for i = 0..N


long[] five = new long[N+1];
for (int i = 0; i <= N; i++)
five[i] = (long) i * i * i * i * i;
System.out.println("Done precomputing fifth powers");
// now do exhaustive search
for (int e = 1; e <= N; e++) {
long e5 = five[e];
// restrict search to a <= b <= c <= d <= e
for (int a = 1; a <= N; a++) {
long a5 = five[a];
if (a5 + a5 + a5 + a5 > e5) break;
for (int b = a; b <= N; b++) {
long b5 = five[b];
if (a5 + b5 + b5 + b5 > e5) break;
for (int c = b; c <= N; c++) {
long c5 = five[c];
if (a5 + b5 + c5 + c5 > e5) break;
for (int d = c; d <= N; d++) {
long d5 = five[d];
if (a5 + b5 + c5 + d5 > e5) break;
if (a5 + b5 + c5 + d5 == e5)
System.out.println(a + "^5 + " + b + "^5 + " + c +
"^5 + " + d + "^5 = " + e + "^5");
}
}
}
}
}
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

Blackjack.java

Below is the syntax highlighted version of Blackjack.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Blackjack.java
* Execution:
java BlackjackEuler x y z
*
* Output the "basic strategy" for blackjack under standard Atlantic
* City rules with 6 decks. Uses precomputed tables.

*
* Reference: http://www.blackjackinfo.com/cgi-bin/bjbse.cgi?game=ac6
*
*
*
*
*************************************************************************/
public class Blackjack {
public static
boolean Y
boolean N
boolean I

void main(String[] args) {


= true;
= false;
= false;
// irrelevant, never used

int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int z = Integer.parseInt(args[2]);
// split[i][j] = should you split with (i, i) if dealer is showing j
boolean[][] split = { { I, I, I, I, I, I, I, I, I, I, I },
{ I, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y },
// A,
A

{ I, N, Y, Y, Y, Y, Y, Y, N, N, N },

//

2,

{ I, N, Y, Y, Y, Y, Y, Y, N, N, N },

//

3,

{ I, N, N, N, N, Y, Y, N, N, N, N },

//

4,

{ I, N, N, N, N, N, N, N, N, N, N },

//

5,

{ I, N, Y, Y, Y, Y, Y, N, N, N, N },

//

6,

{ I, N, Y, Y, Y, Y, Y, Y, N, N, N },

//

7,

{ I, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y },

//

8,

{ I, N, Y, Y, Y, Y, Y, N, Y, Y, N },

//

9,

{ I, N, N, N, N, N, N, N, N, N, N },

// 10,

2
3
4
5
6
7
8
9
10

};
// soft[i][j] = should you hit with (A, i) if dealer is showing j
boolean[][] soft = { { I, I, I, I, I, I, I, I, I, I, I },
{ I, I, I, I, I, I, I, I, I, I, I },
//

A
2
3
4
5
6

A,

{ I, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y },

//

A,

{ I, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y },

//

A,

{ I, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y },

//

A,

{ I, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y },

//

A,

{ I, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y },

//

A,

{ I, Y, N, N, N, N, N, N, N, Y, Y },

//

A,

{ I, N, N, N, N, N, N, N, N, N, N },

//

A,

{ I, N, N, N, N, N, N, N, N, N, N },

//

A,

{ I, N, N, N, N, N, N, N, N, N, N },

//

A,

7
8
9
10
};

// soft[i][j] = should you


boolean[][] hard = { { I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
{ I,
};

hit with
I, I, I,
I, I, I,
I, I, I,
I, I, I,
I, I, I,
Y, Y, Y,
Y, Y, Y,
Y, Y, Y,
Y, Y, Y,
Y, Y, Y,
Y, Y, Y,
Y, Y, Y,
Y, Y, Y,
Y, N, N,
Y, N, N,
Y, N, N,
Y, N, N,
N, N, N,
N, N, N,
N, N, N,

total
I, I,
I, I,
I, I,
I, I,
I, I,
Y, Y,
Y, Y,
Y, Y,
Y, Y,
Y, Y,
Y, Y,
Y, Y,
N, N,
N, N,
N, N,
N, N,
N, N,
N, N,
N, N,
N, N,

= i if dealer
I, I, I, I, I
I, I, I, I, I
I, I, I, I, I
I, I, I, I, I
I, I, I, I, I
Y, Y, Y, Y, Y
Y, Y, Y, Y, Y
Y, Y, Y, Y, Y
Y, Y, Y, Y, Y
Y, Y, Y, Y, Y
Y, Y, Y, Y, Y
Y, Y, Y, Y, Y
N, Y, Y, Y, Y
N, Y, Y, Y, Y
N, Y, Y, Y, Y
N, Y, Y, Y, Y
N, Y, Y, Y, Y
N, N, N, N, N
N, N, N, N, N
N, N, N, N, N

// if y is an ace, flip cards


if (y == 1) { y = x; x = 1; }
// split
if (x == y && split[x][z]) System.out.println("Split");
// a single ace
else if (x == 1) {
if (soft[y][z]) System.out.println("Hit");
else
System.out.println("Stick");
}
// no ace and did not split
else {
if (hard[x+y][z]) System.out.println("Hit");
else
System.out.println("Stick");
}
}
}

is showing j
},
// 0
},
// 1
},
// 2
},
// 3
},
// 4
},
// 5
},
// 6
},
// 7
},
// 8
},
// 9
},
// 10
},
// 11
},
// 12
},
// 13
},
// 14
},
// 15
},
// 16
},
// 17
},
// 18
},
// 19

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:00:59 EST 2011.

Pascal.java

Below is the syntax highlighted version of Pascal.java from 1.4 Arrays.

/*************************************************************************
* Compilation: javac Pascal.java
* Execution:
java Pascal N
*
* Computes and prints out Pascal's triangle or order N.
* Illustrated ragged arrays in Java.
*
* % java Pascal 7
* 1
* 1 1
* 1 2 1
* 1 3 3 1
* 1 4 6 4 1
* 1 5 10 10 5 1
* 1 6 15 20 15 6 1
* 1 7 21 35 35 21 7 1
*
*************************************************************************/
public class Pascal {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int[][] pascal = new int[N+1][];
// initialize first row
pascal[1] = new int[1 + 2];
pascal[1][1] = 1;
// fill in Pascal's triangle
for (int i = 2; i <= N; i++) {
pascal[i] = new int[i + 2];
for (int j = 1; j < pascal[i].length - 1; j++)
pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];
}
// print results
for (int i = 1; i <= N; i++) {
for (int j = 1; j < pascal[i].length - 1; j++) {
System.out.print(pascal[i][j] + " ");
}
System.out.println();
}
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Aug 5 08:32:56 EDT 2011.

RandomSeq.java

Below is the syntax highlighted version of RandomSeq.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac RandomSeq.java
* Execution:
java RandomSeq N
*
* Prints N numbers between 0 and 1.
*
* % java RandomSeq 5
* 0.1654760343787165
* 0.6212262060326124
* 0.631755596883274
* 0.4165639935584283
* 0.4603525361488371
*
*************************************************************************/
public class RandomSeq {
public static void main(String[] args) {
// command-line argument
int N = Integer.parseInt(args[0]);
// generate and print N numbers between 0 and 1
for (int i = 0; i < N; i++) {
System.out.println(Math.random());
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

StdIn.java

Below is the syntax highlighted version of StdIn.java from Standard Libraries. Here is the
Javadoc.

/*************************************************************************
* Compilation: javac StdIn.java
* Execution:
java StdIn
(interactive test of basic functionality)
*

* Reads in data of various types from standard input.


*
*************************************************************************/
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* <i>Standard input</i>. This class provides methods for reading strings
* and numbers from standard input. See
* <a href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
* <p>
* See the technical information in the documentation of the {@link In}
* class, which applies to this class as well.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdIn {
// it doesn't make sense to instantiate this class
private StdIn() {}
private static Scanner scanner;
/*** begin: section (1 of 2) of code duplicated from In to StdIn */
// assume Unicode UTF-8 encoding
private static final String charsetName = "UTF-8";
// assume language = English, country = US for consistency with
System.out.
private static final java.util.Locale usLocale =
new java.util.Locale("en", "US");
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN
= Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace characters significant
private static final Pattern EMPTY_PATTERN
= Pattern.compile("");
// used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private static final Pattern EVERYTHING_PATTERN
= Pattern.compile("\\A");
/*** end: section (1 of 2) of code duplicated from In to StdIn */
/*** begin: section (2 of 2) of code duplicated from In to StdIn,
* with all methods changed from "public" to "public static" ***/
/**

* Is the input empty (except possibly for whitespace)? Use this


* to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*/
public static boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Does the input have a next line? Use this to know whether the
* next call to {@link #readLine()} will succeed. <p> Functionally
* equivalent to {@link #hasNextChar()}.
*/
public static boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Is the input empty (including whitespace)? Use this to know
* whether the next call to {@link #readChar()} will succeed. <p>
Functionally
* equivalent to {@link #hasNextLine()}.
*/
public static boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
/**
* Read and return the next line.
*/
public static String readLine() {
String line;
try
{ line = scanner.nextLine(); }
catch (Exception e) { line = null;
}
return line;
}
/**
* Read and return the next character.
*/
public static char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert (ch.length() == 1) : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
/**
* Read and return the remainder of the input as a string.
*/

public static String readAll() {


if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
/**
* Read and return the next string.
*/
public static String readString() {
return scanner.next();
}
/**
* Read and return the next int.
*/
public static int readInt() {
return scanner.nextInt();
}
/**
* Read and return the next double.
*/
public static double readDouble() {
return scanner.nextDouble();
}
/**
* Read and return the next float.
*/
public static float readFloat() {
return scanner.nextFloat();
}
/**
* Read and return the next long.
*/
public static long readLong() {
return scanner.nextLong();
}
/**
* Read and return the next short.
*/
public static short readShort() {
return scanner.nextShort();
}
/**
* Read and return the next byte.
*/
public static byte readByte() {

return scanner.nextByte();

/**
* Read and return the next boolean, allowing case-insensitive
* "true" or "1" for true, and "false" or "0" for false.
*/
public static boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1"))
return true;
if (s.equals("0"))
return false;
throw new java.util.InputMismatchException();
}
/**
* Read all strings until the end of input is reached, and return them.
*/
public static String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// since trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
String[] decapitokens = new String[tokens.length-1];
for (int i=0; i < tokens.length-1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
/**
* Read all ints until the end of input is reached, and return them.
*/
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
/**
* Read all doubles until the end of input is reached, and return them.
*/
public static double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
/*** end: section (2 of 2) of code duplicated from In to StdIn */
/**

* If StdIn changes, use this to reinitialize the scanner.


*/
private static void resync() {
setScanner(new Scanner(new java.io.BufferedInputStream(System.in),
charsetName));
}
private static void setScanner(Scanner scanner) {
StdIn.scanner = scanner;
StdIn.scanner.useLocale(usLocale);
}
// do this once when StdIn is initialized
static {
resync();
}
/**
* Reads all ints from stdin.
* @deprecated For more consistency, use {@link #readAllInts()}
*/
public static int[] readInts() {
return readAllInts();
}
/**
* Reads all doubles from stdin.
* @deprecated For more consistency, use {@link #readAllDoubles()}
*/
public static double[] readDoubles() {
return readAllDoubles();
}
/**
* Reads all Strings from stdin.
* @deprecated For more consistency, use {@link #readAllStrings()}
*/
public static String[] readStrings() {
return readAllStrings();
}
/**
* Interactive test of basic functionality.
*/
public static void main(String[] args) {
System.out.println("Type a string: ");
String s = StdIn.readString();
System.out.println("Your string was: " + s);
System.out.println();
System.out.println("Type an int: ");
int a = StdIn.readInt();
System.out.println("Your int was: " + a);
System.out.println();

System.out.println("Type a boolean: ");


boolean b = StdIn.readBoolean();
System.out.println("Your boolean was: " + b);
System.out.println();
System.out.println("Type a double: ");
double c = StdIn.readDouble();
System.out.println("Your double was: " + c);
System.out.println();
}
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Tue Sep 17 18:29:24 EDT 2013.

StdOut.java

Below is the syntax highlighted version of StdOut.java from Standard Libraries. Here is the
Javadoc.

/*************************************************************************
* Compilation: javac StdOut.java
* Execution:
java StdOut
*
* Writes data of various types to standard output.
*
*************************************************************************/
import
import
import
import

java.io.OutputStreamWriter;
java.io.PrintWriter;
java.io.UnsupportedEncodingException;
java.util.Locale;

/**
* <i>Standard output</i>. This class provides methods for writing strings
* and numbers to standard output.
* <p>
* For additional documentation, see <a
href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdOut {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String charsetName = "UTF-8";

// assume language = English, country = US for consistency with StdIn


private static final Locale US_LOCALE = new Locale("en", "US");
// send output here
private static PrintWriter out;
// this is called before invoking any methods
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out,
charsetName), true);
}
catch (UnsupportedEncodingException e) { System.out.println(e); }
}
// don't instantiate
private StdOut() { }
// close the output stream (not required)
/**
* Close standard output.
*/
public static void close() {
out.close();
}
/**
* Terminate the current line by printing the line separator string.
*/
public static void println() {
out.println();
}
/**
* Print an object to standard output and then terminate the line.
*/
public static void println(Object x) {
out.println(x);
}
/**
* Print a boolean to standard output and then terminate the line.
*/
public static void println(boolean x) {
out.println(x);
}
/**
* Print a char to standard output and then terminate the line.
*/
public static void println(char x) {
out.println(x);
}
/**
* Print a double to standard output and then terminate the line.

*/
public static void println(double x) {
out.println(x);
}
/**
* Print a float to standard output and then terminate the line.
*/
public static void println(float x) {
out.println(x);
}
/**
* Print an int to standard output and then terminate the line.
*/
public static void println(int x) {
out.println(x);
}
/**
* Print a long to standard output and then terminate the line.
*/
public static void println(long x) {
out.println(x);
}
/**
* Print a short to standard output and then terminate the line.
*/
public static void println(short x) {
out.println(x);
}
/**
* Print a byte to standard output and then terminate the line.
*/
public static void println(byte x) {
out.println(x);
}
/**
* Flush standard output.
*/
public static void print() {
out.flush();
}
/**
* Print an Object to standard output and flush standard output.
*/
public static void print(Object x) {
out.print(x);
out.flush();
}
/**
* Print a boolean to standard output and flush standard output.

*/
public static void print(boolean x) {
out.print(x);
out.flush();
}
/**
* Print a char to standard output and flush standard output.
*/
public static void print(char x) {
out.print(x);
out.flush();
}
/**
* Print a double to standard output and flush standard output.
*/
public static void print(double x) {
out.print(x);
out.flush();
}
/**
* Print a float to standard output and flush standard output.
*/
public static void print(float x) {
out.print(x);
out.flush();
}
/**
* Print an int to standard output and flush standard output.
*/
public static void print(int x) {
out.print(x);
out.flush();
}
/**
* Print a long to standard output and flush standard output.
*/
public static void print(long x) {
out.print(x);
out.flush();
}
/**
* Print a short to standard output and flush standard output.
*/
public static void print(short x) {
out.print(x);
out.flush();
}
/**
* Print a byte to standard output and flush standard output.
*/

public static void print(byte x) {


out.print(x);
out.flush();
}
/**
* Print a formatted string to standard output using the specified
* format string and arguments, and flush standard output.
*/
public static void printf(String format, Object... args) {
out.printf(US_LOCALE, format, args);
out.flush();
}
/**
* Print a formatted string to standard output using the specified
* locale, format string, and arguments, and flush standard output.
*/
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
// This method is just here to test the class
public static void main(String[] args) {

// write to stdout
StdOut.println("Test");
StdOut.println(17);
StdOut.println(true);
StdOut.printf("%.6f\n", 1.0/7.0);

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Tue Sep 17 18:29:24 EDT 2013.

StdDraw.java

Below is the syntax highlighted version of StdDraw.java from Standard Libraries. Here is the
Javadoc.

/*************************************************************************
* Compilation: javac StdDraw.java
* Execution:
java StdDraw
*
* Standard drawing library. This class provides a basic capability for
* creating drawings with your programs. It uses a simple graphics model that
* allows you to create drawings consisting of points, lines, and curves
* in a window on your computer and to save the drawings to a file.

*
* Todo
* ---*
- Add support for gradient fill, etc.
*
- Fix setCanvasSize() so that it can only be called once.
*
* Remarks
* ------*
- don't use AffineTransform for rescaling since it inverts
*
images and strings
*
- careful using setFont in inner loop within an animation *
it can cause flicker
*
*************************************************************************/
import
import
import
import
import
import
import
import
import
import

java.awt.*;
java.awt.event.*;
java.awt.geom.*;
java.awt.image.*;
java.io.*;
java.net.*;
java.util.LinkedList;
java.util.TreeSet;
javax.imageio.ImageIO;
javax.swing.*;

/**
* <i>Standard draw</i>. This class provides a basic capability for
* creating drawings with your programs. It uses a simple graphics model that
* allows you to create drawings consisting of points, lines, and curves
* in a window on your computer and to save the drawings to a file.
* <p>
* For additional documentation, see <a
href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdDraw implements ActionListener, MouseListener,
MouseMotionListener, KeyListener {
// pre-defined colors
public static final Color
public static final Color
public static final Color
public static final Color
public static final Color
public static final Color
public static final Color
public static final Color
public static final Color
public static final Color
public static final Color
public static final Color
public static final Color

BLACK
BLUE
CYAN
DARK_GRAY
GRAY
GREEN
LIGHT_GRAY
MAGENTA
ORANGE
PINK
RED
WHITE
YELLOW

=
=
=
=
=
=
=
=
=
=
=
=
=

Color.BLACK;
Color.BLUE;
Color.CYAN;
Color.DARK_GRAY;
Color.GRAY;
Color.GREEN;
Color.LIGHT_GRAY;
Color.MAGENTA;
Color.ORANGE;
Color.PINK;
Color.RED;
Color.WHITE;
Color.YELLOW;

/**
* Shade of blue used in Introduction to Programming in Java.
* It is Pantone 300U. The RGB values are approximately (9, 90, 166).
*/
public static final Color BOOK_BLUE
= new Color( 9, 90, 166);
public static final Color BOOK_LIGHT_BLUE = new Color(103, 198, 243);
/**
* Shade of red used in Algorithms 4th edition.
* It is Pantone 1805U. The RGB values are approximately (150, 35, 31).
*/
public static final Color BOOK_RED = new Color(150, 35, 31);
// default colors
private static final Color DEFAULT_PEN_COLOR
= BLACK;
private static final Color DEFAULT_CLEAR_COLOR = WHITE;
// current pen color
private static Color penColor;
// default canvas size is DEFAULT_SIZE-by-DEFAULT_SIZE
private static final int DEFAULT_SIZE = 512;
private static int width = DEFAULT_SIZE;
private static int height = DEFAULT_SIZE;
// default pen radius
private static final double DEFAULT_PEN_RADIUS = 0.002;
// current pen radius
private static double penRadius;
// show we draw immediately or wait until next show?
private static boolean defer = false;
// boundary of
private static
private static
private static
private static
private static
private static

drawing canvas, 5% border


final double BORDER = 0.05;
final double DEFAULT_XMIN = 0.0;
final double DEFAULT_XMAX = 1.0;
final double DEFAULT_YMIN = 0.0;
final double DEFAULT_YMAX = 1.0;
double xmin, ymin, xmax, ymax;

// for synchronization
private static Object mouseLock = new Object();
private static Object keyLock = new Object();
// default font
private static final Font DEFAULT_FONT = new Font("SansSerif", Font.PLAIN,

16);

// current font
private static Font font;
// double buffered graphics
private static BufferedImage offscreenImage, onscreenImage;
private static Graphics2D offscreen, onscreen;

// singleton for callbacks: avoids generation of extra .class files


private static StdDraw std = new StdDraw();
// the frame for drawing to the screen
private static JFrame frame;
// mouse state
private static boolean mousePressed = false;
private static double mouseX = 0;
private static double mouseY = 0;
// queue of typed key characters
private static LinkedList<Character> keysTyped = new
LinkedList<Character>();
// set of key codes currently pressed down
private static TreeSet<Integer> keysDown = new TreeSet<Integer>();
// singleton pattern: client can't instantiate
private StdDraw() { }
// static initializer
static { init(); }
/**
* Set the window size to the default size 512-by-512 pixels.
* This method must be called before any other commands.
*/
public static void setCanvasSize() {
setCanvasSize(DEFAULT_SIZE, DEFAULT_SIZE);
}
/**
* Set the window size to w-by-h pixels.
* This method must be called before any other commands.
*
* @param w the width as a number of pixels
* @param h the height as a number of pixels
* @throws a IllegalArgumentException if the width or height is 0 or
negative
*/
public static void setCanvasSize(int w, int h) {
if (w < 1 || h < 1) throw new IllegalArgumentException("width and
height must be positive");
width = w;
height = h;
init();
}
// init
private static void init() {
if (frame != null) frame.setVisible(false);
frame = new JFrame();

offscreenImage = new BufferedImage(width, height,


BufferedImage.TYPE_INT_ARGB);
BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
offscreen = offscreenImage.createGraphics();
>setXscale();
setYscale();
offscreen.setColor(DEFAULT_CLEAR_COLOR);
offscreen.fillRect(0, 0, width, height);
setPenColor();
setPenRadius();
setFont();
clear();
// add antialiasing
RenderingHints hints = new
RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
offscreen.addRenderingHints(hints);
// frame stuff
ImageIcon icon = new ImageIcon(onscreenImage);
JLabel draw = new JLabel(icon);
draw.addMouseListener(std);
draw.addMouseMotionListener(std);
frame.setContentPane(draw);
frame.addKeyListener(std);
// JLabel cannot get keyboard focus
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//
closes all windows
// frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//
closes only current window
frame.setTitle("Standard Draw");
frame.setJMenuBar(createMenuBar());
frame.pack();
frame.requestFocusInWindow();
frame.setVisible(true);
}
// create the menu bar (changed to private)
private static JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem menuItem1 = new JMenuItem(" Save...
");
menuItem1.addActionListener(std);
menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
menu.add(menuItem1);
return menuBar;

}
/*************************************************************************
* User and screen coordinate systems
*************************************************************************/
/**
* Set the x-scale to be the default (between 0.0 and 1.0).
*/
public static void setXscale() { setXscale(DEFAULT_XMIN, DEFAULT_XMAX); }
/**
* Set the y-scale to be the default (between 0.0 and 1.0).
*/
public static void setYscale() { setYscale(DEFAULT_YMIN, DEFAULT_YMAX); }
/**
* Set the x-scale (a 10% border is added to the values)
* @param min the minimum value of the x-scale
* @param max the maximum value of the x-scale
*/
public static void setXscale(double min, double max) {
double size = max - min;
synchronized (mouseLock) {
xmin = min - BORDER * size;
xmax = max + BORDER * size;
}
}
/**
* Set the y-scale (a 10% border is added to the values).
* @param min the minimum value of the y-scale
* @param max the maximum value of the y-scale
*/
public static void setYscale(double min, double max) {
double size = max - min;
synchronized (mouseLock) {
ymin = min - BORDER * size;
ymax = max + BORDER * size;
}
}
/**
* Set the x-scale and y-scale (a 10% border is added to the values)
* @param min the minimum value of the x- and y-scales
* @param max the maximum value of the x- and y-scales
*/
public static void setScale(double min, double max) {
double size = max - min;
synchronized (mouseLock) {
xmin = min - BORDER * size;
xmax = max + BORDER * size;
ymin = min - BORDER * size;
ymax = max + BORDER * size;
}
}

// helper functions that scale from user coordinates to screen coordinates


and back
private static double scaleX(double x) { return width * (x - xmin) /
(xmax - xmin); }
private static double scaleY(double y) { return height * (ymax - y) /
(ymax - ymin); }
private static double factorX(double w) { return w * width /
Math.abs(xmax - xmin); }
private static double factorY(double h) { return h * height /
Math.abs(ymax - ymin); }
private static double
userX(double x) { return xmin + x * (xmax - xmin)
/ width;
}
private static double
userY(double y) { return ymax - y * (ymax - ymin)
/ height;
}
/**
* Clear the screen to the default color (white).
*/
public static void clear() { clear(DEFAULT_CLEAR_COLOR); }
/**
* Clear the screen to the given color.
* @param color the Color to make the background
*/
public static void clear(Color color) {
offscreen.setColor(color);
offscreen.fillRect(0, 0, width, height);
offscreen.setColor(penColor);
draw();
}
/**
* Get the current pen radius.
*/
public static double getPenRadius() { return penRadius; }
/**
* Set the pen size to the default (.002).
*/
public static void setPenRadius() { setPenRadius(DEFAULT_PEN_RADIUS); }
/**
* Set the radius of the pen to the given size.
* @param r the radius of the pen
* @throws IllegalArgumentException if r is negative
*/
public static void setPenRadius(double r) {
if (r < 0) throw new IllegalArgumentException("pen radius must be
nonnegative");
penRadius = r;
float scaledPenRadius = (float) (r * DEFAULT_SIZE);
BasicStroke stroke = new BasicStroke(scaledPenRadius,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
// BasicStroke stroke = new BasicStroke(scaledPenRadius);
offscreen.setStroke(stroke);
}

/**
* Get the current pen color.
*/
public static Color getPenColor() { return penColor; }
/**
* Set the pen color to the default color (black).
*/
public static void setPenColor() { setPenColor(DEFAULT_PEN_COLOR); }
/**
* Set the pen color to the given color. The available pen colors are
* BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA,
* ORANGE, PINK, RED, WHITE, and YELLOW.
* @param color the Color to make the pen
*/
public static void setPenColor(Color color) {
penColor = color;
offscreen.setColor(penColor);
}
/**
* Set the pen color to the given RGB color.
* @param red the amount of red (between 0 and 255)
* @param green the amount of green (between 0 and 255)
* @param blue the amount of blue (between 0 and 255)
* @throws IllegalArgumentException if the amount of red, green, or blue
are outside prescribed range
*/
public static void setPenColor(int red, int green, int blue) {
if (red
< 0 || red
>= 256) throw new
IllegalArgumentException("amount of red must be between 0 and 255");
if (green < 0 || green >= 256) throw new
IllegalArgumentException("amount of red must be between 0 and 255");
if (blue < 0 || blue >= 256) throw new
IllegalArgumentException("amount of red must be between 0 and 255");
setPenColor(new Color(red, green, blue));
}
/**
* Get the current font.
*/
public static Font getFont() { return font; }
/**
* Set the font to the default font (sans serif, 16 point).
*/
public static void setFont() { setFont(DEFAULT_FONT); }
/**
* Set the font to the given value.
* @param f the font to make text
*/
public static void setFont(Font f) { font = f; }
/*************************************************************************

* Drawing geometric shapes.


*************************************************************************/
/**
* Draw a line from (x0, y0) to (x1, y1).
* @param x0 the x-coordinate of the starting point
* @param y0 the y-coordinate of the starting point
* @param x1 the x-coordinate of the destination point
* @param y1 the y-coordinate of the destination point
*/
public static void line(double x0, double y0, double x1, double y1) {
offscreen.draw(new Line2D.Double(scaleX(x0), scaleY(y0), scaleX(x1),
scaleY(y1)));
draw();
}
/**
* Draw one pixel at (x, y).
* @param x the x-coordinate of the pixel
* @param y the y-coordinate of the pixel
*/
private static void pixel(double x, double y) {
offscreen.fillRect((int) Math.round(scaleX(x)), (int)
Math.round(scaleY(y)), 1, 1);
}
/**
* Draw a point at (x, y).
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
*/
public static void point(double x, double y) {
double xs = scaleX(x);
double ys = scaleY(y);
double r = penRadius;
float scaledPenRadius = (float) (r * DEFAULT_SIZE);
// double ws = factorX(2*r);
// double hs = factorY(2*r);
// if (ws <= 1 && hs <= 1) pixel(x, y);
if (scaledPenRadius <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - scaledPenRadius/2, ys scaledPenRadius/2,
scaledPenRadius,
scaledPenRadius));
draw();
}
/**
* Draw a circle of radius r, centered on (x, y).
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @throws IllegalArgumentException if the radius of the circle is
negative
*/
public static void circle(double x, double y, double r) {

if (r < 0) throw new IllegalArgumentException("circle radius must be


nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws,
hs));
draw();
}
/**
* Draw filled circle of radius r, centered on (x, y).
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @throws IllegalArgumentException if the radius of the circle is
negative
*/
public static void filledCircle(double x, double y, double r) {
if (r < 0) throw new IllegalArgumentException("circle radius must be
nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws,
hs));
draw();
}
/**
* Draw an ellipse with given semimajor and semiminor axes, centered on
(x, y).
* @param x the x-coordinate of the center of the ellipse
* @param y the y-coordinate of the center of the ellipse
* @param semiMajorAxis is the semimajor axis of the ellipse
* @param semiMinorAxis is the semiminor axis of the ellipse
* @throws IllegalArgumentException if either of the axes are negative
*/
public static void ellipse(double x, double y, double semiMajorAxis,
double semiMinorAxis) {
if (semiMajorAxis < 0) throw new IllegalArgumentException("ellipse
semimajor axis must be nonnegative");
if (semiMinorAxis < 0) throw new IllegalArgumentException("ellipse
semiminor axis must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*semiMajorAxis);
double hs = factorY(2*semiMinorAxis);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws,
hs));
draw();

}
/**
* Draw an ellipse with given semimajor and semiminor axes, centered on
(x, y).
* @param x the x-coordinate of the center of the ellipse
* @param y the y-coordinate of the center of the ellipse
* @param semiMajorAxis is the semimajor axis of the ellipse
* @param semiMinorAxis is the semiminor axis of the ellipse
* @throws IllegalArgumentException if either of the axes are negative
*/
public static void filledEllipse(double x, double y, double semiMajorAxis,
double semiMinorAxis) {
if (semiMajorAxis < 0) throw new IllegalArgumentException("ellipse
semimajor axis must be nonnegative");
if (semiMinorAxis < 0) throw new IllegalArgumentException("ellipse
semiminor axis must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*semiMajorAxis);
double hs = factorY(2*semiMinorAxis);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws,
hs));
draw();
}
/**
* Draw an arc of radius r, centered on (x, y), from angle1 to angle2 (in
degrees).
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @param angle1 the starting angle. 0 would mean an arc beginning at 3
o'clock.
* @param angle2 the angle at the end of the arc. For example, if
*
you want a 90 degree arc, then angle2 should be angle1 + 90.
* @throws IllegalArgumentException if the radius of the circle is
negative
*/
public static void arc(double x, double y, double r, double angle1, double
angle2) {
if (r < 0) throw new IllegalArgumentException("arc radius must be
nonnegative");
while (angle2 < angle1) angle2 += 360;
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Arc2D.Double(xs - ws/2, ys - hs/2, ws, hs,
angle1, angle2 - angle1, Arc2D.OPEN));
draw();
}
/**

* Draw a square of side length 2r, centered on (x, y).


* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param r radius is half the length of any side of the square
* @throws IllegalArgumentException if r is negative
*/
public static void square(double x, double y, double r) {
if (r < 0) throw new IllegalArgumentException("square side length must
be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws,
hs));
draw();
}
/**
* Draw a filled square of side length 2r, centered on (x, y).
* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param r radius is half the length of any side of the square
* @throws IllegalArgumentException if r is negative
*/
public static void filledSquare(double x, double y, double r) {
if (r < 0) throw new IllegalArgumentException("square side length must
be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws,
hs));
draw();
}
/**
* Draw a rectangle of given half width and half height, centered on (x,
y).

* @param x the x-coordinate of the center of the rectangle


* @param y the y-coordinate of the center of the rectangle
* @param halfWidth is half the width of the rectangle
* @param halfHeight is half the height of the rectangle
* @throws IllegalArgumentException if halfWidth or halfHeight is negative
*/
public static void rectangle(double x, double y, double halfWidth, double
halfHeight) {
if (halfWidth < 0) throw new IllegalArgumentException("half width
must be nonnegative");
if (halfHeight < 0) throw new IllegalArgumentException("half height
must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);

double ws = factorX(2*halfWidth);
double hs = factorY(2*halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws,
hs));

draw();

}
/**
* Draw a filled rectangle of given half width and half height, centered
on (x, y).
* @param x the x-coordinate of the center of the rectangle
* @param y the y-coordinate of the center of the rectangle
* @param halfWidth is half the width of the rectangle
* @param halfHeight is half the height of the rectangle
* @throws IllegalArgumentException if halfWidth or halfHeight is negative
*/
public static void filledRectangle(double x, double y, double halfWidth,
double halfHeight) {
if (halfWidth < 0) throw new IllegalArgumentException("half width
must be nonnegative");
if (halfHeight < 0) throw new IllegalArgumentException("half height
must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfWidth);
double hs = factorY(2*halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws,
hs));
draw();
}
/**
* Draw a polygon with the given (x[i], y[i]) coordinates.
* @param x an array of all the x-coordindates of the polygon
* @param y an array of all the y-coordindates of the polygon
*/
public static void polygon(double[] x, double[] y) {
int N = x.length;
GeneralPath path = new GeneralPath();
path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));
for (int i = 0; i < N; i++)
path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));
path.closePath();
offscreen.draw(path);
draw();
}
/**
* Draw a filled polygon with the given (x[i], y[i]) coordinates.
* @param x an array of all the x-coordindates of the polygon
* @param y an array of all the y-coordindates of the polygon
*/
public static void filledPolygon(double[] x, double[] y) {
int N = x.length;

GeneralPath path = new GeneralPath();


path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));
for (int i = 0; i < N; i++)
path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));
path.closePath();
offscreen.fill(path);
draw();

/*************************************************************************
* Drawing images.
*************************************************************************/
// get an image from the given filename
private static Image getImage(String filename) {
// to read from file
ImageIcon icon = new ImageIcon(filename);
// try to read from URL
if ((icon == null) || (icon.getImageLoadStatus() !=
MediaTracker.COMPLETE)) {
try {
URL url = new URL(filename);
icon = new ImageIcon(url);
} catch (Exception e) { /* not a url */ }
}
// in case file is inside a .jar
if ((icon == null) || (icon.getImageLoadStatus() !=
MediaTracker.COMPLETE)) {
URL url = StdDraw.class.getResource(filename);
if (url == null) throw new IllegalArgumentException("image " +
filename + " not found");
icon = new ImageIcon(url);
}
return icon.getImage();
}
/**
* Draw picture (gif, jpg, or png) centered on (x, y).
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param s the name of the image/picture, e.g., "ball.gif"
* @throws IllegalArgumentException if the image is corrupt
*/
public static void picture(double x, double y, String s) {
Image image = getImage(s);
double xs = scaleX(x);
double ys = scaleY(y);
int ws = image.getWidth(null);
int hs = image.getHeight(null);
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s
+ " is corrupt");

offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int)


Math.round(ys - hs/2.0), null);
draw();
}
/**
* Draw picture (gif, jpg, or png) centered on (x, y),
* rotated given number of degrees
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param s the name of the image/picture, e.g., "ball.gif"
* @param degrees is the number of degrees to rotate counterclockwise
* @throws IllegalArgumentException if the image is corrupt
*/
public static void picture(double x, double y, String s, double degrees) {
Image image = getImage(s);
double xs = scaleX(x);
double ys = scaleY(y);
int ws = image.getWidth(null);
int hs = image.getHeight(null);
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s
+ " is corrupt");
offscreen.rotate(Math.toRadians(-degrees), xs, ys);
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int)
Math.round(ys - hs/2.0), null);
offscreen.rotate(Math.toRadians(+degrees), xs, ys);
draw();
}
/**
* Draw picture (gif, jpg, or png) centered on (x, y), rescaled to w-by-h.
* @param x the center x coordinate of the image
* @param y the center y coordinate of the image
* @param s the name of the image/picture, e.g., "ball.gif"
* @param w the width of the image
* @param h the height of the image
* @throws IllegalArgumentException if the width height are negative
* @throws IllegalArgumentException if the image is corrupt
*/
public static void picture(double x, double y, String s, double w, double

h) {

Image image = getImage(s);


double xs = scaleX(x);
double ys = scaleY(y);
if (w < 0) throw new IllegalArgumentException("width is negative: " +
w);
h);

if (h < 0) throw new IllegalArgumentException("height is negative: " +

double ws = factorX(w);
double hs = factorY(h);
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s
+ " is corrupt");
if (ws <= 1 && hs <= 1) pixel(x, y);
else {

offscreen.drawImage(image, (int)
(int)
(int)
(int)

Math.round(xs - ws/2.0),
Math.round(ys - hs/2.0),
Math.round(ws),
Math.round(hs), null);

}
draw();
}
/**
* Draw picture (gif, jpg, or png) centered on (x, y), rotated
* given number of degrees, rescaled to w-by-h.
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param s the name of the image/picture, e.g., "ball.gif"
* @param w the width of the image
* @param h the height of the image
* @param degrees is the number of degrees to rotate counterclockwise
* @throws IllegalArgumentException if the image is corrupt
*/
public static void picture(double x, double y, String s, double w, double
h, double degrees) {
Image image = getImage(s);
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(w);
double hs = factorY(h);
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s
+ " is corrupt");
if (ws <= 1 && hs <= 1) pixel(x, y);
offscreen.rotate(Math.toRadians(-degrees), xs, ys);
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0),
(int) Math.round(ys - hs/2.0),
(int) Math.round(ws),
(int) Math.round(hs), null);
offscreen.rotate(Math.toRadians(+degrees), xs, ys);
}

draw();

/*************************************************************************
* Drawing text.
*************************************************************************/
/**
* Write the given text string in the current font, centered on (x, y).
* @param x the center x-coordinate of the text
* @param y the center y-coordinate of the text
* @param s the text
*/
public static void text(double x, double y, String s) {
offscreen.setFont(font);
FontMetrics metrics = offscreen.getFontMetrics();
double xs = scaleX(x);
double ys = scaleY(y);

int ws = metrics.stringWidth(s);
int hs = metrics.getDescent();
offscreen.drawString(s, (float) (xs - ws/2.0), (float) (ys + hs));
draw();
}
/**
* Write the given text string in the current font, centered on (x, y) and
* rotated by the specified number of degrees
* @param x the center x-coordinate of the text
* @param y the center y-coordinate of the text
* @param s the text
* @param degrees is the number of degrees to rotate counterclockwise
*/
public static void text(double x, double y, String s, double degrees) {
double xs = scaleX(x);
double ys = scaleY(y);
offscreen.rotate(Math.toRadians(-degrees), xs, ys);
text(x, y, s);
offscreen.rotate(Math.toRadians(+degrees), xs, ys);
}

y).

/**
* Write the given text string in the current font, left-aligned at (x,
* @param x the x-coordinate of the text
* @param y the y-coordinate of the text
* @param s the text
*/
public static void textLeft(double x, double y, String s) {
offscreen.setFont(font);
FontMetrics metrics = offscreen.getFontMetrics();
double xs = scaleX(x);
double ys = scaleY(y);
int hs = metrics.getDescent();
offscreen.drawString(s, (float) (xs), (float) (ys + hs));
draw();
}
/**
* Write the given text string in the current font, right-aligned at (x,

y).

* @param x the x-coordinate of the text


* @param y the y-coordinate of the text
* @param s the text
*/
public static void textRight(double x, double y, String s) {
offscreen.setFont(font);
FontMetrics metrics = offscreen.getFontMetrics();
double xs = scaleX(x);
double ys = scaleY(y);
int ws = metrics.stringWidth(s);
int hs = metrics.getDescent();
offscreen.drawString(s, (float) (xs - ws), (float) (ys + hs));
draw();
}

/**
* Display on screen, pause for t milliseconds, and turn on
* <em>animation mode</em>: subsequent calls to
* drawing methods such as <tt>line()</tt>, <tt>circle()</tt>, and
<tt>square()</tt>
* will not be displayed on screen until the next call to <tt>show()</tt>.
* This is useful for producing animations (clear the screen, draw a bunch
of shapes,
* display on screen for a fixed amount of time, and repeat). It also
speeds up
* drawing a huge number of shapes (call <tt>show(0)</tt> to defer drawing
* on screen, draw the shapes, and call <tt>show(0)</tt> to display them
all
* on screen at once).
* @param t number of milliseconds
*/
public static void show(int t) {
defer = false;
draw();
try { Thread.sleep(t); }
catch (InterruptedException e) { System.out.println("Error sleeping");
}
defer = true;
}
/**
* Display on-screen and turn off animation mode:
* subsequent calls to
* drawing methods such as <tt>line()</tt>, <tt>circle()</tt>, and
<tt>square()</tt>
* will be displayed on screen when called. This is the default.
*/
public static void show() {
defer = false;
draw();
}
// draw onscreen if defer is false
private static void draw() {
if (defer) return;
onscreen.drawImage(offscreenImage, 0, 0, null);
frame.repaint();
}
/*************************************************************************
* Save drawing to a file.
*************************************************************************/
/**
* Save onscreen image to file - suffix must be png, jpg, or gif.
* @param filename the name of the file with one of the required suffixes
*/
public static void save(String filename) {

File file = new File(filename);


String suffix = filename.substring(filename.lastIndexOf('.') + 1);
// png files
if (suffix.toLowerCase().equals("png")) {
try { ImageIO.write(onscreenImage, suffix, file); }
catch (IOException e) { e.printStackTrace(); }
}
// need to change from ARGB to RGB for jpeg
// reference: http://archives.java.sun.com/cgi-bin/wa?
A2=ind0404&L=java2d-interest&D=0&P=2727
else if (suffix.toLowerCase().equals("jpg")) {
WritableRaster raster = onscreenImage.getRaster();
WritableRaster newRaster;
newRaster = raster.createWritableChild(0, 0, width, height, 0, 0,
new int[] {0, 1, 2});
DirectColorModel cm = (DirectColorModel)
onscreenImage.getColorModel();
DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(),
cm.getRedMask(),
cm.getGreenMask(),
cm.getBlueMask());
BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster,
false, null);
try { ImageIO.write(rgbBuffer, suffix, file); }
catch (IOException e) { e.printStackTrace(); }
}
else {
System.out.println("Invalid image file type: " + suffix);
}
}
/**
* This method cannot be called directly.
*/
public void actionPerformed(ActionEvent e) {
FileDialog chooser = new FileDialog(StdDraw.frame, "Use a .png or .jpg
extension", FileDialog.SAVE);
chooser.setVisible(true);
String filename = chooser.getFile();
if (filename != null) {
StdDraw.save(chooser.getDirectory() + File.separator +
chooser.getFile());
}
}
/*************************************************************************
* Mouse interactions.
*************************************************************************/
/**
* Is the mouse being pressed?
* @return true or false

*/
public static boolean mousePressed() {
synchronized (mouseLock) {
return mousePressed;
}
}
/**
* What is the x-coordinate of the mouse?
* @return the value of the x-coordinate of the mouse
*/
public static double mouseX() {
synchronized (mouseLock) {
return mouseX;
}
}
/**
* What is the y-coordinate of the mouse?
* @return the value of the y-coordinate of the mouse
*/
public static double mouseY() {
synchronized (mouseLock) {
return mouseY;
}
}
/**
* This method cannot be called directly.
*/
public void mouseClicked(MouseEvent e) { }
/**
* This method cannot be called directly.
*/
public void mouseEntered(MouseEvent e) { }
/**
* This method cannot be called directly.
*/
public void mouseExited(MouseEvent e) { }
/**
* This method cannot be called directly.
*/
public void mousePressed(MouseEvent e) {
synchronized (mouseLock) {
mouseX = StdDraw.userX(e.getX());
mouseY = StdDraw.userY(e.getY());
mousePressed = true;
}
}
/**
* This method cannot be called directly.
*/

public void mouseReleased(MouseEvent e) {


synchronized (mouseLock) {
mousePressed = false;
}
}
/**
* This method cannot be called directly.
*/
public void mouseDragged(MouseEvent e) {
synchronized (mouseLock) {
mouseX = StdDraw.userX(e.getX());
mouseY = StdDraw.userY(e.getY());
}
}
/**
* This method cannot be called directly.
*/
public void mouseMoved(MouseEvent e) {
synchronized (mouseLock) {
mouseX = StdDraw.userX(e.getX());
mouseY = StdDraw.userY(e.getY());
}
}
/*************************************************************************
* Keyboard interactions.
*************************************************************************/
/**
* Has the user typed a key?
* @return true if the user has typed a key, false otherwise
*/
public static boolean hasNextKeyTyped() {
synchronized (keyLock) {
return !keysTyped.isEmpty();
}
}
/**
* What is the next key that was typed by the user? This method returns
* a Unicode character corresponding to the key typed (such as 'a' or
'A').
* It cannot identify action keys (such as F1
* and arrow keys) or modifier keys (such as control).
* @return the next Unicode key typed
*/
public static char nextKeyTyped() {
synchronized (keyLock) {
return keysTyped.removeLast();
}
}
/**

* Is the keycode currently being pressed? This method takes as an


argument
* the keycode (corresponding to a physical key). It can handle action
keys
* (such as F1 and arrow keys) and modifier keys (such as shift and
control).
* See <a href =
"http://download.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html">Ke
yEvent.java</a>
* for a description of key codes.
* @return true if keycode is currently being pressed, false otherwise
*/
public static boolean isKeyPressed(int keycode) {
synchronized (keyLock) {
return keysDown.contains(keycode);
}
}
/**
* This method cannot be called directly.
*/
public void keyTyped(KeyEvent e) {
synchronized (keyLock) {
keysTyped.addFirst(e.getKeyChar());
}
}
/**
* This method cannot be called directly.
*/
public void keyPressed(KeyEvent e) {
synchronized (keyLock) {
keysDown.add(e.getKeyCode());
}
}
/**
* This method cannot be called directly.
*/
public void keyReleased(KeyEvent e) {
synchronized (keyLock) {
keysDown.remove(e.getKeyCode());
}
}

/**
* Test client.
*/
public static void main(String[] args) {
StdDraw.square(.2, .8, .1);
StdDraw.filledSquare(.8, .8, .2);
StdDraw.circle(.8, .2, .2);

StdDraw.setPenColor(StdDraw.BOOK_RED);
StdDraw.setPenRadius(.02);
StdDraw.arc(.8, .2, .1, 200, 45);
// draw a blue diamond
StdDraw.setPenRadius();
StdDraw.setPenColor(StdDraw.BOOK_BLUE);
double[] x = { .1, .2, .3, .2 };
double[] y = { .2, .3, .2, .1 };
StdDraw.filledPolygon(x, y);
// text
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(0.2, 0.5, "black text");
StdDraw.setPenColor(StdDraw.WHITE);
StdDraw.text(0.8, 0.8, "white text");
}
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Tue Oct 29 07:10:27 EDT 2013.

StdAudio.java

Below is the syntax highlighted version of StdAudio.java from Standard Libraries. Here is the
Javadoc.

/*************************************************************************
* Compilation: javac StdAudio.java
* Execution:
java StdAudio
*
* Simple library for reading, writing, and manipulating .wav files.
*
* Limitations
* ----------*
- Does not seem to work properly when reading .wav files from a .jar
file.
*
- Assumes the audio is monaural, with sampling rate of 44,100.
*
*************************************************************************/
import
import
import
import

java.applet.*;
java.io.*;
java.net.*;
javax.sound.sampled.*;

/**
* <i>Standard audio</i>. This class provides a basic capability for
* creating, reading, and saving audio.

* <p>
* The audio format uses a sampling rate of 44,100 (CD quality audio), 16bit, monaural.
*
* <p>
* For additional documentation, see <a
href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdAudio {
/**
* The sample rate - 44,100 Hz for CD quality audio.
*/
public static final int SAMPLE_RATE = 44100;
private
audio
private
audio
private
private

static final int BYTES_PER_SAMPLE = 2;

// 16-bit

static final int BITS_PER_SAMPLE = 16;

// 16-bit

static final double MAX_16_BIT = Short.MAX_VALUE;


static final int SAMPLE_BUFFER_SIZE = 4096;

// 32,767

private static SourceDataLine line;


private static byte[] buffer;
private static int bufferSize = 0;
internal buffer

// to play the sound


// our internal buffer
// number of samples currently in

// do not instantiate
private StdAudio() { }
// static initializer
static { init(); }
// open up an audio stream
private static void init() {
try {
// 44,100 samples per second, 16-bit audio, mono, signed PCM,
little Endian
AudioFormat format = new AudioFormat((float) SAMPLE_RATE,
BITS_PER_SAMPLE, 1, true, false);
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
format);
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE);
// the internal buffer is a fraction of the actual buffer size,
this choice is arbitrary
// it gets divided because we can't expect the buffered data to
line up exactly with when

// the sound card decides to push out its samples.


buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE/3];
} catch (Exception e) {
System.out.println(e.getMessage());
System.exit(1);
}

// no sound gets made before this call


line.start();

/**
* Close standard audio.
*/
public static void close() {
line.drain();
line.stop();
}
/**
* Write one sample (between -1.0 and +1.0) to standard audio. If the
sample
* is outside the range, it will be clipped.
*/
public static void play(double in) {
// clip if outside [-1, +1]
if (in < -1.0) in = -1.0;
if (in > +1.0) in = +1.0;
// convert to bytes
short s = (short) (MAX_16_BIT * in);
buffer[bufferSize++] = (byte) s;
buffer[bufferSize++] = (byte) (s >> 8);

// little Endian

// send to sound card if buffer is full


if (bufferSize >= buffer.length) {
line.write(buffer, 0, buffer.length);
bufferSize = 0;
}

/**
* Write an array of samples (between -1.0 and +1.0) to standard audio. If
a sample
* is outside the range, it will be clipped.
*/
public static void play(double[] input) {
for (int i = 0; i < input.length; i++) {
play(input[i]);
}
}
/**
* Read audio samples from a file (in .wav or .au format) and return them
as a double array

* with values between -1.0 and +1.0.


*/
public static double[] read(String filename) {
byte[] data = readByte(filename);
int N = data.length;
double[] d = new double[N/2];
for (int i = 0; i < N/2; i++) {
d[i] = ((short) (((data[2*i+1] & 0xFF) << 8) + (data[2*i] &
0xFF))) / ((double) MAX_16_BIT);
}
return d;
}

/**
* Play a sound file (in .wav, .mid, or .au format) in a background
thread.
*/
public static void play(String filename) {
URL url = null;
try {
File file = new File(filename);
if (file.canRead()) url = file.toURI().toURL();
}
catch (MalformedURLException e) { e.printStackTrace(); }
// URL url = StdAudio.class.getResource(filename);
if (url == null) throw new RuntimeException("audio " + filename + "
not found");
AudioClip clip = Applet.newAudioClip(url);
clip.play();
}
/**
* Loop a sound file (in .wav, .mid, or .au format) in a background
thread.
*/
public static void loop(String filename) {
URL url = null;
try {
File file = new File(filename);
if (file.canRead()) url = file.toURI().toURL();
}
catch (MalformedURLException e) { e.printStackTrace(); }
// URL url = StdAudio.class.getResource(filename);
if (url == null) throw new RuntimeException("audio " + filename + "
not found");
AudioClip clip = Applet.newAudioClip(url);
clip.loop();
}
// return data as a byte array
private static byte[] readByte(String filename) {
byte[] data = null;
AudioInputStream ais = null;

try {
// try to read from file
File file = new File(filename);
if (file.exists()) {
ais = AudioSystem.getAudioInputStream(file);
data = new byte[ais.available()];
ais.read(data);
}
// try to read from URL
else {
URL url = StdAudio.class.getResource(filename);
ais = AudioSystem.getAudioInputStream(url);
data = new byte[ais.available()];
ais.read(data);
}

}
catch (Exception e) {
System.out.println(e.getMessage());
throw new RuntimeException("Could not read " + filename);
}
return data;
}

/**
* Save the double array as a sound file (using .wav or .au format).
*/
public static void save(String filename, double[] input) {
// assumes 44,100 samples per second
// use 16-bit audio, mono, signed PCM, little Endian
AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 1, true, false);
byte[] data = new byte[2 * input.length];
for (int i = 0; i < input.length; i++) {
int temp = (short) (input[i] * MAX_16_BIT);
data[2*i + 0] = (byte) temp;
data[2*i + 1] = (byte) (temp >> 8);
}
// now save the file
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
AudioInputStream ais = new AudioInputStream(bais, format,
input.length);
if (filename.endsWith(".wav") || filename.endsWith(".WAV")) {
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new
File(filename));
}
else if (filename.endsWith(".au") || filename.endsWith(".AU")) {
AudioSystem.write(ais, AudioFileFormat.Type.AU, new
File(filename));
}
else {

filename);

throw new RuntimeException("File format not supported: " +

}
}
catch (Exception e) {
System.out.println(e);
System.exit(1);
}
}

/***********************************************************************
* sample test client
***********************************************************************/
// create a note (sine wave) of the given frequency (Hz), for the given
// duration (seconds) scaled to the given volume (amplitude)
private static double[] note(double hz, double duration, double amplitude)
{

int N = (int) (StdAudio.SAMPLE_RATE * duration);


double[] a = new double[N+1];
for (int i = 0; i <= N; i++)
a[i] = amplitude * Math.sin(2 * Math.PI * i * hz /
StdAudio.SAMPLE_RATE);
return a;
}
/**
* Test client - play an A major scale to standard audio.
*/
public static void main(String[] args) {
// 440 Hz for 1 sec
double freq = 440.0;
for (int i = 0; i <= StdAudio.SAMPLE_RATE; i++) {
StdAudio.play(0.5 * Math.sin(2*Math.PI * freq * i /
StdAudio.SAMPLE_RATE));
}
// scale increments
int[] steps = { 0, 2, 4, 5, 7, 9, 11, 12 };
for (int i = 0; i < steps.length; i++) {
double hz = 440.0 * Math.pow(2, steps[i] / 12.0);
StdAudio.play(note(hz, 1.0, 0.5));
}
// need to call this in non-interactive stuff so the program doesn't
terminate
// until all the sound leaves the speaker.
StdAudio.close();
// need to terminate a Java program with sound
System.exit(0);
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Tue Sep 17 18:32:30 EDT 2013.

AddInts.java

Below is the syntax highlighted version of AddInts.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac AddInts.java
* Execution:
java AddInts
* Dependencies: StdIn.java
*
* This program takes a command line argument N, reads in N integers,
* and prints out their sum.
*
* Note: you must hav the file StdIn.java in your working directory.
*
* % java AddInts N
*
*************************************************************************/
public class AddInts
{
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
int sum = 0;
for (int i = 0; i < N; i++)
sum = sum + StdIn.readInt();
System.out.println("Sum is " + sum);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

TwentyQuestions.java

Below is the syntax highlighted version of TwentyQuestions.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac TwentyQuestions.java

* Execution:
java TwentyQuestions
* Dependencies StdIn.java
*
* % java TwentyQuestions
* I'm thinking of a number between 1 and 1,000,000
* What's your guess? 500000
* Too high
* What's your guess? 250000
* Too low
* What's your guess? 375000
* Too high
* What's your guess? 312500
* Too high
* What's your guess? 300500
* Too low
* ...
*
*************************************************************************/
public class TwentyQuestions {
public static void main(String[] args) {
// Generate a number and answer questions
// while the user tries to guess the value.
int N = 1 + (int) (Math.random() * 1000000);
StdOut.print("I'm thinking of a number ");
StdOut.println("between 1 and 1,000,000");
int m = 0;
while (m != N) {
// Solicit one guess and provide one answer
StdOut.print("What's your guess? ");
m = StdIn.readInt();
if (m == N) StdOut.println("You win!");
if (m < N) StdOut.println("Too low ");
if (m > N) StdOut.println("Too high");
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Average.java

Below is the syntax highlighted version of Average.java from 1.5 Input and Output.

/*************************************************************************

*
*
*
*
*
*
*
*
*
*
*

Compilation: javac Average.java


Execution:
java Average < data.txt
Dependencies: StdIn.java StdOut.java
Reads in a sequence of real numbers, and computes their average.
% java Average
10.0 5.0 6.0
3.0 7.0 32.0
<Ctrl-d>
Average is 10.5

* Note <Ctrl-d> signifies the end of file on Unix.


* On windows use <Ctrl-z>.
*
*************************************************************************/
public class Average {
public static void main(String[] args) {
int count = 0;
// number input values
double sum = 0.0;
// sum of input values
// read data and compute statistics
while (!StdIn.isEmpty()) {
double value = StdIn.readDouble();
sum += value;
count++;
}
// compute the average
double average = sum / count;
// print results
StdOut.println("Average is " + average);
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Triangle.java

Below is the syntax highlighted version of Triangle.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Triangle.java
* Execution:
java Triangle
* Dependencies: StdDraw.java
*
* Plot a triangle.
*

*************************************************************************/
public class Triangle {
public static void main(String[] args) {
double t = Math.sqrt(3.0) / 2.0;
StdDraw.line(0.0, 0.0, 1.0, 0.0);
StdDraw.line(1.0, 0.0, 0.5, t);
StdDraw.line(0.5, t, 0.0, 0.0);
StdDraw.point(0.5, t/3.0);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

PlotFilter.java

Below is the syntax highlighted version of PlotFilter.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac PlotFilter.java
* Execution:
java PlotFilter < input.txt
* Dependencies: StdDraw.java StdIn.java
*
* % java PlotFilter < USA.txt
*
* Datafiles:
http://www.cs.princeton.edu/IntroProgramming/15inout/USA.txt
*
*************************************************************************/
public class PlotFilter {
public static void main(String[] args) {
// read in bounding box and rescale
double x0 = StdIn.readDouble();
double y0 = StdIn.readDouble();
double x1 = StdIn.readDouble();
double y1 = StdIn.readDouble();
StdDraw.setXscale(x0, x1);
StdDraw.setYscale(y0, y1);
// turn on animation mode to defer displaying all of the points
// StdDraw.show(0);
// plot points, one at a time
while (!StdIn.isEmpty()) {
double x = StdIn.readDouble();
double y = StdIn.readDouble();
StdDraw.point(x, y);

}
// display all of the points now
// StdDraw.show(0);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

FunctionGraph.java

Below is the syntax highlighted version of FunctionGraph.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac FunctionGraph.java
* Execution:
java FunctionGraph
* Dependencies: StdDraw.java
*
* Plots the function y = sin(4x) + sin(20x) between x = 0 and x = pi
* by drawing N line segments.
*
*************************************************************************/
public class FunctionGraph {
public static void main(String[] args) {
// number of line segments to plot
int N = Integer.parseInt(args[0]);
// the function y = sin(4x) + sin(20x), sampled at N points
// between x = 0 and x = pi
double[] x = new double[N+1];
double[] y = new double[N+1];
for (int i = 0; i <= N; i++) {
x[i] = Math.PI * i / N;
y[i] = Math.sin(4*x[i]) + Math.sin(20*x[i]);
}
// rescale the coordinate system
StdDraw.setXscale(0, Math.PI);
StdDraw.setYscale(-2.0, +2.0);
// plot the approximation to the function
for (int i = 0; i < N; i++) {
StdDraw.line(x[i], y[i], x[i+1], y[i+1]);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

BouncingBall.java

Below is the syntax highlighted version of BouncingBall.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac BouncingBall.java
* Execution:
java BouncingBall
* Dependencies: StdDraw.java
*
* Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1).
*
* % java BouncingBall
*
*************************************************************************/
public class BouncingBall {
public static void main(String[] args) {
// set the scale of the coordinate system
StdDraw.setXscale(-1.0, 1.0);
StdDraw.setYscale(-1.0, 1.0);
// initial values
double rx = 0.480, ry = 0.860;
double vx = 0.015, vy = 0.023;
double radius = 0.05;

// position
// velocity
// radius

// main animation loop


while (true) {
// bounce off wall according to law of elastic collision
if (Math.abs(rx + vx) > 1.0 - radius) vx = -vx;
if (Math.abs(ry + vy) > 1.0 - radius) vy = -vy;
// update position
rx = rx + vx;
ry = ry + vy;
// clear the background
StdDraw.setPenColor(StdDraw.GRAY);
StdDraw.filledSquare(0, 0, 1.0);
// draw ball on the screen
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.filledCircle(rx, ry, radius);

}
}

// display and pause for 20 ms


StdDraw.show(20);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

DeluxeBouncingBall.java

Below is the syntax highlighted version of DeluxeBouncingBall.java from 1.5 Input and
Output.

/*************************************************************************
* Compilation: javac DeluxeBouncingBall.java
* Execution:
java DeluxeBouncingBall
* Dependencies: StdDraw.java StdAudio.java
*
http://www.cs.princeton.edu/introcs/15inout/laser.wav
*
http://www.cs.princeton.edu/introcs/15inout/pop.wav
*
http://www.cs.princeton.edu/introcs/15inout/earth.gif
*
* Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1).
*
* % java DeluxeBouncingBall
*
*************************************************************************/
public class DeluxeBouncingBall {
public static void main(String[] args) {
double rx = .480, ry = .860;
// position
double vx = .015, vy = .023;
// velocity
double radius = .03;
// a hack since "earth.gif" is in
pixels
// set the scale of the coordinate system
StdDraw.setXscale(-1.0, 1.0);
StdDraw.setYscale(-1.0, 1.0);
// main animation loop
while (true) {
if (Math.abs(rx + vx) + radius > 1.0) { vx = -vx;
StdAudio.play("laser.wav"); }
if (Math.abs(ry + vy) + radius > 1.0) { vy = -vy;
StdAudio.play("pop.wav");
}
rx = rx + vx;
ry = ry + vy;
StdDraw.filledSquare(0.0, 0.0, 1.0);
StdDraw.picture(rx, ry, "earth.gif");
StdDraw.show(20);
}
}
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Thu Sep 29 12:38:11 EDT 2011.

MouseFollower.java

Below is the syntax highlighted version of MouseFollower.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac MouseFollower.java
* Execution:
java MouseFollower
* Dependencies: StdDraw.java
*
* Draw a blue filled circle wherever the mouse is, in cyan if the
* mouse is pressed.
*
*
* % java MouseFollower
*
* Credits: Jeff Traer-Bernstein
*
*************************************************************************/
public class MouseFollower {
public static void main(String[] args) {
while (true) {
// mouse click
if (StdDraw.mousePressed()) StdDraw.setPenColor(StdDraw.CYAN);
else
StdDraw.setPenColor(StdDraw.BLUE);

}
}

// mouse location
StdDraw.clear();
double x = StdDraw.mouseX();
double y = StdDraw.mouseY();
StdDraw.filledCircle(x, y, .05);
StdDraw.show(10);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

OneSimpleAttractor.java

Below is the syntax highlighted version of OneSimpleAttractor.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac OneSimpleAttractor.java
* Execution:
java OneSimpleAttractor
* Dependencies: StdDraw.java
*
* A particle is attracted to the current location of the mouse.
* Incorporates drag.
*
*
* % java OneSimpleAttractor
*
*
* Credits: Jeff Traer-Bernstein
*
*************************************************************************/

public class OneSimpleAttractor {


public static void main(String[] args) {
double rx = 0.0, ry = 0.0;
// position
double vx = 0.0, vy = 0.0;
// velocity
double mass = 1.0;
// mass
double dt
= 0.5;
// time quantum
double drag = 0.1;
// mess around with this a bit
double attractionStrength = 0.01;
// do the animation
while (true) {
// compute the attractive force to the mouse, accounting for drag
double dx = StdDraw.mouseX() - rx;
double dy = StdDraw.mouseY() - ry;
double fx = (dx * attractionStrength) - (drag * vx);
double fy = (dy * attractionStrength) - (drag * vy);
//
vx
vy
rx
ry

}
}

Euler
+= fx
+= fy
+= vx
+= vy

step: update velocity, then position


* dt / mass;
* dt / mass;
* dt;
* dt;

// draw particle
StdDraw.clear();
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.filledCircle(rx, ry, .02);
StdDraw.show(10);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

SimpleAttractors.java

Below is the syntax highlighted version of SimpleAttractors.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac SimpleAttractors.java
* Execution:
java SimpleAttractors N
* Dependencies: StdDraw.java
*
* N particles are attracted to the mouse; randomly rearrange when
* user clicks.
*
* % java SimpleAttractors 20
*
* Credits: Jeff Traer-Bernstein
*
*************************************************************************/
public class SimpleAttractors {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
double[] rx = new double[N];
double[] ry = new double[N];
double[] vx = new double[N];
double[] vy = new double[N];
double dt = 0.5;
double mass = 1.0;
double drag = 0.05;
// try changing this to 0.1 or 0.01 or even
0...
double attractionStrength = 0.01;
// initialize the drawing area
StdDraw.setPenColor(StdDraw.BLUE);
// do the animation
while (true) {
// if the mouse is pressed add some random velocity to all the
particles
if (StdDraw.mousePressed()) {
for (int i = 0; i < N; i++) {
vx[i] = .2 * Math.random() - .1;
vy[i] = .2 * Math.random() - .1;
}
}
// clear all the forces
double[] fx = new double[N];
double[] fy = new double[N];

// add attraction forces for attraction to the mouse


for (int i = 0; i < N; i++) {
double dx = StdDraw.mouseX() - rx[i];
double dy = StdDraw.mouseY() - ry[i];
fx[i] += attractionStrength * dx;
fy[i] += attractionStrength * dy;
}
// add drag forces to all particles
// drag is proportional to velocity in the opposite direction
for (int i = 0; i < N; i++) {
fx[i] += -drag * vx[i];
fy[i] += -drag * vy[i];
}
// update positions
// euler step
for (int i = 0; i < N; i++) {
vx[i] += fx[i] * dt / mass;
vy[i] += fy[i] * dt / mass;
rx[i] += vx[i] * dt;
ry[i] += vy[i] * dt;
}
StdDraw.clear();
// draw a filled circle for each particle
for (int i = 0; i < N; i++) {
StdDraw.filledCircle(rx[i], ry[i], .01);
}
}
}

StdDraw.show(10);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Springs.java

Below is the syntax highlighted version of Springs.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Springs.java
* Execution:
java Springs N
* Dependencies: StdDraw.java
*
* Simulates a system of springs.

*
* % java Springs 15
*
* Credits: Jeff Traer-Bernstein
*
*************************************************************************/
public class Springs {
public static void main(String[] args) {
// mess around with this, try 7, 8, 9, 10, 11, 12, 15
// probably have to turn down the spring force to keep it stable after
that...
int N = Integer.parseInt(args[0]);
double[] rx = new double[N];
double[] ry = new double[N];
double[] vy = new double[N];
double[] vx = new double[N];
double particleMass = 1.0;
double drag = 0.1;
double springStrength = 0.1;
double springLength = 30;
double gravity = 1.0;
double timeStep = 0.5;
// set up the drawing area
StdDraw.setXscale(0, 100);
StdDraw.setYscale(0, 100);
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.setPenRadius(0.0025);
// initialize the
for (int i = 0; i
rx[i] = 100 *
ry[i] = 100 *
}

particle positions randomly


< N; i++) {
Math.random();
Math.random();

// do the animation
while (true) {
// clear all the forces
double[] fx = new double[N];
double[] fy = new double[N];
// spring forces act between every pairing of particles
// spring force is proportional to the difference between the rest
length of the spring
// and the distance between the 2 particles it's acting on
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) continue;
// calculate distance between particles i and j
double dx = rx[j] - rx[i];

double dy = ry[j] - ry[i];


double length = Math.sqrt(dx*dx + dy*dy);
// figure out the force
double force = springStrength * (length - springLength);
double springForceX = force * dx / length;
double springForceY = force * dy / length;

// update the force


fx[i] += springForceX;
fy[i] += springForceY;

}
// add drag force
// drag is proportional to velocity but in the opposite direction
for (int i = 0; i < N; i++) {
fx[i] += -drag * vx[i];
fy[i] += -drag * vy[i];
}
// add gravity forces
// just add some force pointing down to all of them
for (int i = 0; i < N; i++) {
fy[i] += -gravity;
}
// fix particle 1 at the mouse position
rx[0] = StdDraw.mouseX();
ry[0] = StdDraw.mouseY();
vx[0] = 0.0;
vy[0] = 0.0;
fx[0] = 0.0;
fy[0] = 0.0;
// update positions using approximation
for (int i = 0; i < N; i++) {
vx[i] += fx[i] * timeStep/particleMass;
vy[i] += fy[i] * timeStep/particleMass;
rx[i] += vx[i] * timeStep;
ry[i] += vy[i] * timeStep;
}
// clear
StdDraw.clear();
// draw everything
for (int i = 0; i < N; i++) {
// draw a circle for each node
StdDraw.filledCircle(rx[i], ry[i], 1.0);
// draw the connections between every 2 nodes
for (int j = 0; j < i; j++) {
StdDraw.line(rx[i], ry[i], rx[j], ry[j]);
}
}

}
}

// show and wait


StdDraw.show(10);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

PlayThatTune.java

Below is the syntax highlighted version of PlayThatTune.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac PlayThatTune.java
* Execution:
java PlayThatTune < input.txt
* Dependencies: StdAudio.java StdAudio.java
*
* This is a data-driven program that plays pure tones from
* the notes on the chromatic scale, specified on standard input
* by their distance from concert A.
*
* % java PlayThatTune < elise.txt
*
*
* Data files
* ---------* http://www.cs.princeton.edu/introcs/21function/elise.txt
* http://www.cs.princeton.edu/introcs/21function/99luftballons.txt
* http://www.cs.princeton.edu/introcs/21function/freebird.txt
* http://www.cs.princeton.edu/introcs/21function/Ascale.txt
* http://www.cs.princeton.edu/introcs/21function/National_Anthem.txt
* http://www.cs.princeton.edu/introcs/21function/looney.txt
* http://www.cs.princeton.edu/introcs/21function/StairwayToHeaven.txt
* http://www.cs.princeton.edu/introcs/21function/entertainer.txt
* http://www.cs.princeton.edu/introcs/21function/old-nassau.txt
* http://www.cs.princeton.edu/introcs/21function/arabesque.txt
* http://www.cs.princeton.edu/introcs/21function/firstcut.txt
* http://www.cs.princeton.edu/introcs/21function/tomsdiner.txt
*
*************************************************************************/
public class PlayThatTune {
public static void main(String[] args) {
// repeat as long as there are more integers to read in
while (!StdIn.isEmpty()) {
// read in the pitch, where 0 = Concert A (A4)

int pitch = StdIn.readInt();


// read in duration in seconds
double duration = StdIn.readDouble();
// build sine wave with desired frequency
double hz = 440 * Math.pow(2, pitch / 12.0);
int N = (int) (StdAudio.SAMPLE_RATE * duration);
double[] a = new double[N+1];
for (int i = 0; i <= N; i++) {
a[i] = Math.sin(2 * Math.PI * i * hz / StdAudio.SAMPLE_RATE);
}

}
}

// play it using standard audio


StdAudio.play(a);

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Oct 12 08:44:49 EDT 2011.

MaxMin.java

Below is the syntax highlighted version of MaxMin.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac MaxMin.java
* Execution:
java MaxMin
*
[ input required from standard input
]
*
[ use Ctrl-d (OS X or Dr. Java) or Ctrl-z (Windows) for EOF ]
*
* Dependencies: StdIn.java StdOut.java
*
* Read in integers from standard input and print out the maximum and
* minimum values.
*
* % java MaxMin
* 23 45 17 56 32
* 89 10 53 32 34
* 16
* Ctrl-d
* maximum = 89, minimum = 10
*
*************************************************************************/
public class MaxMin {
public static void main(String[] args) {
// first value read initialized min and max
int max = StdIn.readInt();

int min = max;


// read in the data, keep track of min and max
while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
if (value > max) max = value;
if (value < min) min = value;
}

// output
StdOut.println("maximum

= " + max + ", minimum = " + min);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Stats.java

Below is the syntax highlighted version of Stats.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Stats.java
* Execution:
java Stats N
* Dependencies: StdIn.java StdOut.java
*
* Reads in a command-line integer N, a sequence of N real numbers from
* standard input, and prints the mean and standard deviation.
*
* % java Stats 6
* 10.0 5.0 6.0
* 3.0 7.0 32.0
* <Ctrl-d>
* Mean
= 10.5
* Standard deviation = 4.822862220714997
*
* Note <Ctrl-d> signifies the end of file on Unix.
* On windows use <Ctrl-z>.
*
*************************************************************************/
public class Stats {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
double[] a = new double[N];
// read data and compute statistics
for (int i = 0; i < N; i++) {
a[i] = StdIn.readDouble();
}

// compute mean
double sum = 0.0;
for (int i = 0; i < N; i++) {
sum += a[i];
}
double mean = sum / N;
// compute standard deviation
double sum2 = 0.0;
for (int i = 0; i < N; i++) {
sum2 += (a[i] - mean) * (a[i] - mean);
}
double stddev = Math.sqrt(sum2) / (N - 1);
// print results
StdOut.println("Mean
= " + mean);
StdOut.println("Standard deviation = " + stddev);
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

LongestRun.java

Below is the syntax highlighted version of LongestRun.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac LongestRun.java
* Execution:
java LongestRun
*
[ input required from standard input
]
*
[ use Ctrl-d (OS X or Dr. Java) or Ctrl-z (Windows) for EOF ]
*
* Dependencies: StdIn.java StdOut.java
*
* Read in a sequence of integers and prints out both the integer
* that appears in a longest consecutive run and length of the run.
*
* % java LongestRun
* 1 2 2 1 5 1 1 7 7 7 7 1 1
* Ctrl-d
* Longest run: 4 consecutive 7s
*
*************************************************************************/
public class LongestRun {
public static void main(String[] args) {
// degenerate case with no input integers
if (StdIn.isEmpty()) {

StdOut.println("no longest consecutive run");


return;
}
int
int
int
int

prev = StdIn.readInt();
count = 1;
best
= prev;
bestCount = count;

while (!StdIn.isEmpty()) {
// read in the next value
int current = StdIn.readInt();
// update current run
if (current == prev) count++;
else {
prev = current;
count = 1;
}

"s");
}
}

// update champion values


if (count > bestCount) {
bestCount = count;
best
= current;
}

// output
StdOut.println("Longest run: " + bestCount + " consecutive " + best +

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Dragon.java

Below is the syntax highlighted version of Dragon.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Dragon.java
* Execution:
echo F F | java Dragon | java Dragon | java Dragon
*
* Prints the instructions for drawing a dragon curve of orders N.
*
* % echo F F | java Dragon
* FLF FRF
*

* % echo F F | java Dragon | java Dragon


* FLFLFRF FLFRFRF
*
* % echo F F | java Dragon | java Dragon | java Dragon
* FLFLFRFLFLFRFRF FLFLFRFRFLFRFRF
*
*************************************************************************/
public class Dragon {
public static void main(String[] args) {
String dragon = StdIn.readString();
String nogard = StdIn.readString();
System.out.print(dragon + "L" + nogard);
System.out.print(" ");
System.out.print(dragon + "R" + nogard);
System.out.println();
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

WordCount.java

Below is the syntax highlighted version of WordCount.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac WordCount.java
* Execution:
java WordCount
*
[ input required from standard input
]
*
[ use Ctrl-d (OS X or Dr. Java) or Ctrl-z (Windows) for EOF ]
*
* Dependencies: StdIn.java StdOut.java
*
* Read in a sequence of strings from standard input and print out
* the number of strings read in.
*
* % java WordCount
* it was the best of times
* it was the worst of times
* number of words = 12
* Ctrl-d
*
* % java WordCount < tale.txt
* number of words = 139043
*
*************************************************************************/
public class WordCount {
public static void main(String[] args) {

int count = 0;
while (!StdIn.isEmpty()) {
String word = StdIn.readString();
count++;
}

// output
StdOut.println("number of words

= " + count);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Closest.java

Below is the syntax highlighted version of Closest.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Closest.java
* Execution:
java Closest x y z
*
[ input required from standard input
]
*
[ use Ctrl-d (OS X or Dr. Java) or Ctrl-z (Windows) for EOF ]
*
* Dependencies: StdIn.java StdOut.java
*
* Takes three command-line arguments x, y, z; reads from standard input a
* sequence of point coordinates (xi, yi, zi), and prints the coordinates
* of the point closest to (x, y, z).
*
* % java Closest 1.0 5.0 2.0
* 1.0 3.0 9.0
* 5.0 3.0 2.5
* 9.0 6.0 2.0
* 2.0 6.0 3.0
* 5.0 6.0 5.0
* <Ctrl-d>
* Closest point = (2.000000, 6.000000, 3.000000)
*
*************************************************************************/
public class Closest {
public static void main(String[] args) {
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
double z = Double.parseDouble(args[2]);
double bestx = Double.NaN;
double besty = Double.NaN;

double bestz = Double.NaN;


double bestDist2 = Double.POSITIVE_INFINITY;
while (!StdIn.isEmpty()) {
double xi = StdIn.readDouble();
double yi = StdIn.readDouble();
double zi = StdIn.readDouble();
double dist2 = (x - xi) * (x - xi) + (y - yi) * (y - yi) + (z zi) * (z - zi);
if (dist2 < bestDist2) {
bestx = xi;
besty = yi;
bestz = zi;
bestDist2 = dist2;
}
}

// output
StdOut.printf("Closest point = (%f, %f, %f)\n", bestx, besty, bestz);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

CheckerBoard.java

Below is the syntax highlighted version of CheckerBoard.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac CheckerBoard.java
* Execution:
java CheckerBoard N
* Dependencies: StdDraw.java
*
* Plots an N-by-N checker board.
*
*************************************************************************/
public class CheckerBoard {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
StdDraw.setXscale(0, N);
StdDraw.setYscale(0, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if ((i + j) % 2 != 0) StdDraw.setPenColor(StdDraw.BLACK);
else
StdDraw.setPenColor(StdDraw.RED);
StdDraw.filledSquare(i + .5, j + .5, .5);

}
}
StdDraw.show();

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Mon Feb 14 07:19:37 EST 2011.

Rose.java

Below is the syntax highlighted version of Rose.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Rose.java
* Execution:
java Rose N
* Dependencies: StdDraw.java
*
* Plots an N petal rose (if N is odd) and a 2N-petal rose if N is
* even, using standard graphics.
*
*************************************************************************/
public class Rose {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
StdDraw.setXscale(-1, +1);
StdDraw.setYscale(-1, +1);
StdDraw.setPenColor(StdDraw.PINK);

double x0 = 0, y0 = 0;
for (double t = 0.0; t <= 360.0; t += 0.1) {
double theta = Math.toRadians(t);
double r = Math.sin(N * theta);
double x1 = r * Math.cos(theta);
double y1 = r * Math.sin(theta);
StdDraw.line(x0, y0, x1, y1);
x0 = x1;
y0 = y1;
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Banner.java

Below is the syntax highlighted version of Banner.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Banner.java
* Execution:
java Banner s
* Dependencies: StdDraw.java
*
* Plots the String s, and moves it across the screen, left-to-right,
* wrapping around when it reaches the border.
*
* % java Banner "Hello, World"
*
*
*************************************************************************/
import java.awt.Font;
public class Banner {
public static void main(String[] args) {
String s = args[0];
// remove the 5% border
StdDraw.setXscale(1.0/22.0, 21.0/22.0);
StdDraw.setYscale(1.0/22.0, 21.0/22.0);
// set the font
Font f = new Font("Arial", Font.BOLD, 60);
StdDraw.setFont(f);
StdDraw.setPenColor(StdDraw.WHITE);
for (double i = 0.0; true; i += 0.01) {
StdDraw.clear(StdDraw.BLACK);
StdDraw.text((i % 1.0),
0.5, s);
StdDraw.text((i % 1.0) - 1.0, 0.5, s);
StdDraw.text((i % 1.0) + 1.0, 0.5, s);
StdDraw.show(60);
}
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

PlayThatTune.java

Below is the syntax highlighted version of PlayThatTune.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac PlayThatTune.java
* Execution:
java PlayThatTune < input.txt
* Dependencies: StdAudio.java StdAudio.java
*
* This is a data-driven program that plays pure tones from
* the notes on the chromatic scale, specified on standard input
* by their distance from concert A.
*
* % java PlayThatTune < elise.txt
*
*
* Data files
* ---------* http://www.cs.princeton.edu/introcs/21function/elise.txt
* http://www.cs.princeton.edu/introcs/21function/99luftballons.txt
* http://www.cs.princeton.edu/introcs/21function/freebird.txt
* http://www.cs.princeton.edu/introcs/21function/Ascale.txt
* http://www.cs.princeton.edu/introcs/21function/National_Anthem.txt
* http://www.cs.princeton.edu/introcs/21function/looney.txt
* http://www.cs.princeton.edu/introcs/21function/StairwayToHeaven.txt
* http://www.cs.princeton.edu/introcs/21function/entertainer.txt
* http://www.cs.princeton.edu/introcs/21function/old-nassau.txt
* http://www.cs.princeton.edu/introcs/21function/arabesque.txt
* http://www.cs.princeton.edu/introcs/21function/firstcut.txt
* http://www.cs.princeton.edu/introcs/21function/tomsdiner.txt
*
*************************************************************************/
public class PlayThatTune {
public static void main(String[] args) {
// repeat as long as there are more integers to read in
while (!StdIn.isEmpty()) {
// read in the pitch, where 0 = Concert A (A4)
int pitch = StdIn.readInt();
// read in duration in seconds
double duration = StdIn.readDouble();
// build sine wave with desired frequency
double hz = 440 * Math.pow(2, pitch / 12.0);
int N = (int) (StdAudio.SAMPLE_RATE * duration);
double[] a = new double[N+1];
for (int i = 0; i <= N; i++) {
a[i] = Math.sin(2 * Math.PI * i * hz / StdAudio.SAMPLE_RATE);
}

// play it using standard audio


StdAudio.play(a);
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Oct 12 08:44:49 EDT 2011.

Spirograph.java

Below is the syntax highlighted version of Spirograph.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Spirograph.java
* Execution:
java Spirograph R r a
* Dependencies: StdDraw.java
*
* Draw a curve formed by rolling a smaller circle of radius r inside
* a larger circle or radius R. If the pen offset of the pen point in
* the moving circle is a, then the equation of the resulting curve
* at time t is
*
*
x = (R+r)*cos(t) - (r+a)*cos(((R+r)/r)*t)
*
y = (R+r)*sin(t) - (r+a)*sin(((R+r)/r)*t)
*
* % java Spirograph 180 40 15
*
* % java Spirograph 100 55 20
*
* Credits: idea suggested by Diego Nehab
* Reference: http://www.math.dartmouth.edu/~dlittle/java/SpiroGraph
* Reference: http://www.wordsmith.org/~anu/java/spirograph.html
*
*************************************************************************/
public class Spirograph {
public static void main(String[] args) {
double R = Double.parseDouble(args[0]);
double r = Double.parseDouble(args[1]);
double a = Double.parseDouble(args[2]);
StdDraw.setXscale(-300, +300);
StdDraw.setYscale(-300, +300);
StdDraw.clear(StdDraw.BLACK);
for (double t = 0.0;
double x = (R+r)
double y = (R+r)
double degrees =

t < 100; t += 0.01) {


* Math.cos(t) - (r+a) * Math.cos(((R+r)/r)*t);
* Math.sin(t) - (r+a) * Math.sin(((R+r)/r)*t);
-Math.toDegrees((R+r)/r)*t;

StdDraw.picture(x, y, "earth.gif", degrees);


// StdDraw.rotate(+Math.toDegrees((R+r)/r)*t);
StdDraw.show(20);

}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Clock.java

Below is the syntax highlighted version of Clock.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Clock.java
* Execution:
java Clock
* Dependencies: StdDraw.java
*
*************************************************************************/
public class Clock {
public static void main(String[] args) {
for (int t = 0; true; t++) {
// remainder operator with doubles so all hands move every second
double seconds = t % 60;
double minutes = (t / 60.0) % 60;
double hours
= (t / 3600.0) % 12;
StdDraw.clear(StdDraw.LIGHT_GRAY);
StdDraw.setPenRadius();
// clock face
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.filledCircle(0.5, 0.5, 0.45);
// hour markers
StdDraw.setPenColor(StdDraw.BLUE);
for (int i = 0; i < 12; i++) {
double theta = Math.toRadians(i * 30);
StdDraw.filledCircle(0.5 + 0.4 * Math.cos(theta), 0.5 + 0.4 *
Math.sin(theta), .025);
}
// second hand

StdDraw.setPenRadius(.01);
StdDraw.setPenColor(StdDraw.YELLOW);
double angle1 = Math.toRadians(6 * seconds);
double r1 = 0.4;
StdDraw.line(0.5, 0.5, 0.5 + r1 * Math.sin(angle1), 0.5 + r1 *
Math.cos(angle1));
// minute hand
StdDraw.setPenRadius(.02);
StdDraw.setPenColor(StdDraw.GRAY);
double angle2 = Math.toRadians(6 * minutes);
double r2 = 0.3;
StdDraw.line(0.5, 0.5, 0.5 + r2 * Math.sin(angle2), 0.5 + r2 *
Math.cos(angle2));
// hour hand
StdDraw.setPenRadius(.025);
StdDraw.setPenColor(StdDraw.WHITE);
double angle3 = Math.toRadians(30 * hours);
double r3 = 0.2;
StdDraw.line(0.5, 0.5, 0.5 + r3 * Math.sin(angle3), 0.5 + r3 *
Math.cos(angle3));
// digital time
int second = t
% 60;
int minute = (t / 60)
% 60;
int hour
= (t / 3600) % 12;
String time = String.format("%2d:%02d:%02d", hour, minute,
second);

StdDraw.setPenColor(StdDraw.BOOK_RED);
StdDraw.text(0.5, 0.0, time);
// 1000 miliseconds = 1 second
StdDraw.show(1000);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Oscilloscope.java

Below is the syntax highlighted version of Oscilloscope.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Oscilloscope.java
* Execution:
java Oscilloscope A B wX wY phiX phiY
* Dependencies: StdDraw.java
*

* Simluate the output of an oscilloscope. Assume that the vertical and


* horizontal inputs are sinusoidal.
*
*
x = A sin (wX + phiX)
*
y = B sin (wY + phiY)
*
* % java Oscilloscope 1 1 2 3 20 45
*
*************************************************************************/
public class Oscilloscope {
public static void main(String[] args) {
StdDraw.setXscale(-1, +1);
StdDraw.setYscale(-1, +1);
double
double
double
double
double
double

A
B
wX
wY
phiX
phiY

=
=
=
=
=
=

Double.parseDouble(args[0]);
Double.parseDouble(args[1]);
Double.parseDouble(args[2]);
Double.parseDouble(args[3]);
Double.parseDouble(args[4]);
Double.parseDouble(args[5]);

// amplitudes
// angular frequencies
// phase factors

// convert from degrees to radians


phiY = Math.toRadians(phiX);
phiY = Math.toRadians(phiY);
for (double t = 0.0; t < 10; t += 0.0001) {
double x = A * Math.sin(wX * t + phiX);
double y = B * Math.sin(wY * t + phiY);
StdDraw.point(x, y);
StdDraw.show(10);
}
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

RunLengthEncoder.java

Below is the syntax highlighted version of RunLengthEncoder.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac RunLengthEncoder.java
* Execution:
java RunLengthEncoder < data.txt
* Dependencies: StdIn.java
*

* Reads in a sequence of 0's and 1's and encodes using RLE.


*
* % java RunLengthEncoder
* 00001111000011111
* 4 4 4 5
*
*************************************************************************/
public class RunLengthEncoder {
public static void main(String[] args) {
char last = '0';
int count = 0;
while (!StdIn.isEmpty()) {
char c = StdIn.readChar();
// new line
if (c == '\n') {
System.out.println("" + count);
count = 0;
last = '0';
}
// validate input
else if ((c != '0') && (c != '1'))
throw new RuntimeException("Invalid input");
// repeated character
else if (c == last) count++;
// changes from 0 to 1 or from 1 to 0
else {
System.out.print(count + " ");
count = 1;
last = c;
}

}
System.out.println(count);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Globe.java

Below is the syntax highlighted version of Globe.java from 1.5 Input and Output.

/*************************************************************************

* Compilation: javac Globe.java


* Execution:
java Globe N
* Dependencies: StdDraw.java
*
* Plots a globe with angle angle.
*
*************************************************************************/
public class Globe {
public static void main(String[] args) {
double alpha = Double.parseDouble(args[0]);
StdDraw.setYscale(-1, +1);
StdDraw.setXscale(-1, +1);
StdDraw.setPenColor(StdDraw.BLUE);
double x0 = 1, y0 = 0;
for (double t = 0.0; t <= 20 * 360.0; t += 0.1) {
double theta = Math.toRadians(t);
double r = Math.cos(alpha * theta);
double x1 = r * Math.cos(theta);
double y1 = r * Math.sin(theta);
StdDraw.line(x0, y0, x1, y1);
x0 = x1;
y0 = y1;
}
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

RandomText.java

Below is the syntax highlighted version of RandomText.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac RandomText.java
* Execution:
java RandomText s N
* Dependencies: StdDraw.java
*
* Plots the String s, N times at random locations, and in random
* colors.
*
* % java RandomText Hello 10
*
* % java RandomText World 15
*
* % java RandomText Java 20

*
*
*************************************************************************/
import java.awt.Color;
import java.awt.Font;
public class RandomText {
public static void main(String[] args) {
String s = args[0];
int N = Integer.parseInt(args[1]);
StdDraw.clear(Color.BLACK);
Font f = new Font("Arial", Font.BOLD, 60);
StdDraw.setFont(f);
for (int i = 0; i < N; i++) {
StdDraw.setPenColor(Color.getHSBColor((float) Math.random(), 1.0f,
1.0f));

double x = Math.random();
double y = Math.random();
StdDraw.text(x, y, s);
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

RandomWalk.java

Below is the syntax highlighted version of RandomWalk.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac RandomWalk.java
* Execution:
java RandomWalk N
* Dependencies: StdDraw.java
*
* % java RandomWalk 20
* total steps = 300
*
* % java RandomWalk 50
* total steps = 2630
*
* Simulates a 2D random walk and plots the trajectory.
*
* Remarks: works best if N is a divisor of 600.
*
*************************************************************************/

public class RandomWalk {


public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
StdDraw.setXscale(-N, +N);
StdDraw.setYscale(-N, +N);
StdDraw.clear(StdDraw.GRAY);
int x = 0, y = 0;
int steps = 0;
while (Math.abs(x) < N && Math.abs(y) < N) {
StdDraw.setPenColor(StdDraw.WHITE);
StdDraw.filledSquare(x, y, 0.45);
double r = Math.random();
if
(r < 0.25) x--;
else if (r < 0.50) x++;
else if (r < 0.75) y--;
else if (r < 1.00) y++;
steps++;
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.filledSquare(x, y, .45);
StdDraw.show(40);
}
System.out.println("Total steps = " + steps);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

BallisticMotion.java

Below is the syntax highlighted version of BallisticMotion.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac BallisticMotion.java
* Execution:
java BallisticMotion v theta
* Dependencies: StdDraw.java
*
* Simluate the motion of a ball fired with velocity v at theta degrees
* with coefficient of drag C. Uses Euler-Cramer method to numerically
* solve differential equation.
*
* % java BallisticMotion 180.0 60.0
*
* % java BallisticMotion 20.0 45.0
*
*************************************************************************/

public class BallisticMotion {


public static void main(String[] args) {
double G = 9.8;
// gravitational constant m/s^2
double C = 0.002;
// drag force coefficient
double v
= Double.parseDouble(args[0]);
velocity
double theta = Math.toRadians(Double.parseDouble(args[1]));
in radians

force

//
// angle

double x = 0.0, y = 0.0;


double vx = v * Math.cos(theta);
double vy = v * Math.sin(theta);

// position
// velocity in x direction
// velocity in y direction

double ax = 0.0, ay = 0.0;


double t = 0.0;
double dt = 0.01;

// acceleration
// time
// time quantum

double maxR = v*v / G;

// maximum distance without drag

StdDraw.setXscale(0, maxR);
StdDraw.setYscale(0, maxR);

// set the same as for X-scale

// loop until ball hits ground


while (y >= 0.0) {
v = Math.sqrt(vx*vx + vy*vy);
ax = -C * v * vx;
ay = -G - C * v * vy;
vx += ax * dt;
vy += ay * dt;
x += vx * dt;
y += vy * dt;
StdDraw.filledCircle(x, y, 0.25);
StdDraw.show(5);
}
StdDraw.show();

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Tue Sep 3 15:03:40 EDT 2013.

Heart.java

Below is the syntax highlighted version of Heart.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Heart.java

* Execution:
java Heart
* Dependencies: StdDraw.java
*
* Draw a pink heart (a filled diamond plus two filled circles).
*
*************************************************************************/
public class Heart {
public static void main(String[] args) {
StdDraw.setXscale(-1.5, +1.5);
StdDraw.setYscale(-1.5, +1.5);
StdDraw.setPenColor(StdDraw.PINK);
// draw diamond
double[] xs = { -1, 0, 1, 0 };
double[] ys = { 0, -1, 0, 1 };
StdDraw.filledPolygon(xs, ys);

// circles
StdDraw.filledCircle(+0.5, 0.5, 1 / Math.sqrt(2));
StdDraw.filledCircle(-0.5, 0.5, 1 / Math.sqrt(2));

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Madness.java

Below is the syntax highlighted version of Madness.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Madness.java
* Execution:
java Madness
*
* Plots a parametric figure which A. K. Dewdney refers to as
* Miller's Madness.
*
* Reference: The Magic Machine by A. K. Dewdney. This figure
* was designed by Stanley S. Miller, a management consultant.
*
*
*************************************************************************/
public class Madness {
public static void main(String[] args) {
StdDraw.setXscale(-1.7, +1.7);
StdDraw.setYscale(-1.1, +1.1);

double x0 = -0.7, y0 = 1.0;


for (double t = 0.0; true; t += 0.01) {
double x1 = Math.sin(0.99*t) - 0.7*Math.cos(3.01*t);
double y1 = Math.cos(1.01*t) + 0.1*Math.sin(15.03*t);
StdDraw.line(x0, y0, x1, y1);
x0 = x1;
y0 = y1;
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Butterfly.java

Below is the syntax highlighted version of Butterfly.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Butterfly.java
* Execution:
java Butterfly
* Dependencies: StdDraw.java
*
* Plots a butterfly-like curve.
*
* Reference: A. K. Dewdney's The Magic Machine. Credited to
* Temple H. Fay of the University of Southern Mississippi.
*
*************************************************************************/
public class Butterfly {
public static void main(String[] args) {
StdDraw.setXscale(-4, 4);
StdDraw.setYscale(-4, 4);
double x0 = 0, y0 = 0;
for (double theta = 0.0; theta < 72; theta += 0.01) {
double r = Math.exp(Math.cos(theta)) - 2*Math.cos(4*theta) +
Math.pow(Math.sin(theta/12), 5);
double x1 = r * Math.cos(theta);
double y1 = r * Math.sin(theta);
StdDraw.line(x0, y0, x1, y1);
x0 = x1;
y0 = y1;
}
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Students.java

Below is the syntax highlighted version of Students.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Students.java
* Execution:
java Students < students.txt
* Dependencies: StdIn.java
* Sample data: http://introcs.cs.princeton.edu/15inout/students.txt
*
* Reads in the integer N from standard input, then a list
* of N student records, where each record consists of four
* fields, separated by whitespace:
*
- first name
*
- last name
*
- email address
*
- which section they're in
*
* Then, print out a list of email address of students in section 4 and 5.
*
* % 130
* Sarah Wang twang 7
* Austin Taylor actaylor 1
* David Rosner drosner 4
* Rebecca Allen rebeccaa 7
* Rajiv Ayyangar ayyangar 7
* Daniel Barrett drbarret 8
* Nic Byrd nbyrd 7
* Emily Capra ecapra 8
* Johnny Clore jclore 7
* ...
*
* % Section 4
* --------* drosner
* jcharles
* jph
* mlampert
* ...
*
* Section 5
* --------* giwank
* agrozdan
* ajh
* akornell
* ...
*
*************************************************************************/

public class Students {


public static void main(String[] args) {
// read the number of students
int N = StdIn.readInt();
// initialize four parallel arrays
String[] first = new String[N];
String[] last = new String[N];
String[] email = new String[N];
int[] section = new int[N];
// read in the data
for (int i = 0; i < N; i++) {
first[i]
= StdIn.readString();
last[i]
= StdIn.readString();
email[i]
= StdIn.readString();
section[i] = StdIn.readInt();
}
// print email addresses of all students in section 4
StdOut.println("Section 4");
StdOut.println("---------");
for (int i = 0; i < N; i++) {
if (section[i] == 4) {
StdOut.println(email[i]);
}
}
StdOut.println();
// print email addresses of all students in section 5
StdOut.println("Section 5");
StdOut.println("---------");
for (int i = 0; i < N; i++) {
if (section[i] == 5) {
StdOut.println(email[i]);
}
}
}
}

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Tue Feb 15 11:58:40 EST 2011.

Shuffle.java

Below is the syntax highlighted version of Shuffle.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Shuffle.java
* Execution:
java Shuffle N < california-gov.txt
* Dependencies: StdIn.java
*
* Reads in N lines of text, shuffles them, and print them in random order.
* Uses Knuth's shuffling shuffle.
*
* The file california-gov.txt contains a list of the 135
* candidates in the October 7, 2003 California governor's runoff
* election. The file cards.txt contains a list of 52 playing cards.
*
*
* % java Shuffle 5 < california-gov.txt
* Iris Adam
* Douglas Anderson
* Alex-St. James
* Angelyne
* Brooke Adams
*
* % java Shuffle 5 < cards.txt
* Four of Clubs
* Six of Clubs
* Three of Clubs
* Deuce of Clubs
* Five of Clubs
*
*
*************************************************************************/
public class Shuffle {
// swaps array elements i and j
public static void exch(String[] a, int i, int j) {
String swap = a[i];
a[i] = a[j];
a[j] = swap;
}
// take as input an array of strings and rearrange them in random order
public static void shuffle(String[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + (int) (Math.random() * (N-i));
// between i and N-1
exch(a, i, r);
}
}
// take as input an array of strings and print them out to standard output
public static void show(String[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}

public static void main(String[] args) {


int N = Integer.parseInt(args[0]);
String[] a = new String[N];
// read in data
for (int i = 0; i < N; i++) {
a[i] = StdIn.readLine();
}
// shuffle array and print permutation
shuffle(a);
show(a);
System.out.println();
// do it again
shuffle(a);
show(a);
}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Reverse.java

Below is the syntax highlighted version of Reverse.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Reverse.java StdIn.java
* Execution:
java Reverse
*
* Reads in real numbers and prints them in reverse order. Uses an
* array and repeatedly doubles its size if necessary.
*
* % java Reverse
* 1.0 2.0 3.0 4.0 5.0 6.0 5.9 5.8 5.7
* <Ctrl-d>
* 5.7 5.8 5.9 6.0 5.0 4.0 3.0 2.0 1.0
*
* Windows users: use <Ctrl-z> instead of <Ctrl-d> to signify EOF.
*
*************************************************************************/
class Reverse {
public static void main(String[] args) {
int N = 0;
// number of elements in array
double[] data = new double[1];
// initialze array capacity = 1
while (!StdIn.isEmpty()) {

// double the size of the array if necessary


if (N == data.length) {
double[] temp = new double[2*N];
for (int i = 0; i < N; i++) temp[i] = data[i];
data = temp;
}
// read in the next value
data[N++] = StdIn.readDouble();
}
// print it out
for (int i = N-1; i >= 0; i--)
System.out.print(data[i] + " ");
System.out.println();
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

CollidingBalls.java

Below is the syntax highlighted version of CollidingBalls.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac CollidingBalls.java
* Execution:
java CollidingBalls N
* Dependencies: StdDraw.java
*
* Simulate N balls of uniform mass, bouncing off the four walls
* and each other according to the laws of elastic collisions.
*
* % java CollidingBalls 50
*
* Limitations
* ----------*
- Inefficient since it performs N^2 collision checks per dt.
*
*
- Can miss collisions. Use event-based simulation and a priority
*
queue instead of time-based simulation to fix.
*
*
- physics not correct
*
*************************************************************************/
import java.awt.Color;
public class CollidingBalls {

public static void main(String[] args) {


int N = Integer.parseInt(args[0]);
double dt = 1.0;
double RADIUS = 5.0;
// initialize positions and velocities at random
double[] px = new double[N];
double[] py = new double[N];
double[] vx = new double[N];
double[] vy = new double[N];
Color[] color = new Color[N];
for (int i = 0; i < N; i++) {
px[i] = 16 + 480 * Math.random();
py[i] = 16 + 480 * Math.random();
vx[i] = 10 * Math.random() - 5;
vy[i] = 10 * Math.random() - 5;
color[i] = Color.getHSBColor((float) Math.random(), 1.0f, 1.0f);
}
int SIZE = 512;
StdDraw.setXscale(0, SIZE);
StdDraw.setYscale(0, SIZE);
while (true) {
StdDraw.clear(Color.BLACK);
// detect collision with wall and reverse velocity
for (int i = 0; i < N; i++) {
if ((px[i] + dt * vx[i] > SIZE - RADIUS) || (px[i] + dt *
vx[i] < RADIUS)) vx[i] = -vx[i];
if ((py[i] + dt * vy[i] > SIZE - RADIUS) || (py[i] + dt *
vy[i] < RADIUS)) vy[i] = -vy[i];
}
// detect collision with other particles
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
double dx = (px[i] - px[j]) + dt * (vx[i] - vx[j]);
double dy = (py[i] - py[j]) + dt * (vy[i] - vy[j]);
// if collision swap velocities
if (Math.sqrt(dx*dx + dy*dy) <= 2*RADIUS) {
double tempx = vx[i];
double tempy = vy[i];
vx[i] = vx[j];
vy[i] = vy[j];
vx[j] = tempx;
vy[j] = tempy;
StdAudio.play("pop.wav");
break;
// only pairwise collisions
}
}

// update positions
for (int i = 0; i < N; i++) {

px[i] = px[i] + vx[i] * dt;


py[i] = py[i] + vy[i] * dt;
}
// update positions
for (int i = 0; i < N; i++) {
StdDraw.setPenColor(color[i]);
StdDraw.filledCircle(px[i], py[i], RADIUS);
}
StdDraw.show(50);
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Duke.java

Below is the syntax highlighted version of Duke.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Duke.java
* Execution:
java Duke
* Dependencies: StdDraw.java StdIn.java
*
* Draw the sequence of images T1.gif to T17.gif. This creates
* the illusion of motion, where the Java mascot Duke cart-wheels
* across the screen.
*
* Reference:
http://java.sun.com/docs/books/tutorial/uiswing/components/example1dot4/index.html#TumbleItem
*
*************************************************************************/
public class Duke {
public static void main(String[] args) {
int images = 17;
int WIDTH = 130, HEIGHT = 80;
StdDraw.setCanvasSize(WIDTH, HEIGHT);
StdDraw.setXscale(0, WIDTH);
StdDraw.setYscale(0, HEIGHT);

// number of images
// images are 130-by-80

// main animation loop


for (int t = 0; true; t++) {
int i = 1 + (t % images);
String filename = "T" + i + ".gif"; // name of the ith image
StdDraw.picture(WIDTH/2.0, HEIGHT/2.0, filename);
StdDraw.show(100);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

MoreDuke.java

Below is the syntax highlighted version of MoreDuke.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac MoreDuke.java
* Execution:
java MoreDuke
* Dependencies: StdDraw.java StdIn.java T[1-17].gif
*
* Make Duke cartwheel across the screen from right to left, wrapping
* around.
*
* Reference:
http://java.sun.com/docs/books/tutorial/uiswing/components/example1dot4/index.h$
*
*************************************************************************/
public class MoreDuke {
public static void main(String[] args) {
// image width = 130-by-80
int IMAGES
= 17;
int CARTWHEELS = 5;
int CYCLES
= 100;
int OVERLAP
= 57;
carthweels
int WIDTH
= OVERLAP * CARTWHEELS;
int HEIGHT
= 80;
StdDraw.setCanvasSize(WIDTH, HEIGHT);
StdDraw.setXscale(0, WIDTH);
StdDraw.setYscale(0, HEIGHT);

//
//
//
//

images per cartwheel


cartwheels per cycle
number of cycles
overlap between two

// width of the window


// height of the window

// main animation loop


int x = WIDTH * CYCLES;
for (int t = 0; t < CYCLES; t++) {
x -= OVERLAP;
for (int i = 1; i <= IMAGES; i++) {
StdDraw.clear();
String filename = "T" + i + ".gif";
// name of ith image
StdDraw.picture(
x % WIDTH, HEIGHT/2.0, filename);
StdDraw.picture(WIDTH + x % WIDTH, HEIGHT/2.0, filename);

StdDraw.show(100);
}
StdDraw.show(1000);

}
}

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

QuestionsTwenty.java

Below is the syntax highlighted version of QuestionsTwenty.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac QuestionsTwenty.java
* Execution:
java QuestionsTwenty
* Dependencies StdIn.java
*
* Think of an integer between 0 and 1000000.
* Truthfully answer 'true' or 'false' to each question I ask.
*
* Q1: Is your number <= 500000?
* true
* Q2: Is your number <= 250000?
* true
* Q3: Is your number <= 125000?
* true
* Q4: Is your number <= 62500?
* false
* Q5: Is your number <= 93750?
* true
* Q6: Is your number <= 78125?
* false
* Q7: Is your number <= 85938?
* true
* Q8: Is your number <= 82032?
* true
* Q9: Is your number <= 80079?
* false
* Q10: Is your number <= 81056?
* true
* Q11: Is your number <= 80568?
* true
* Q12: Is your number <= 80324?
* false
* Q13: Is your number <= 80446?

* true
* Q14: Is your number <= 80385?
* true
* Q15: Is your number <= 80355?
* true
* Q16: Is your number <= 80340?
* false
* Q17: Is your number <= 80348?
* true
* Q18: Is your number <= 80344?
* true
* Q19: Is your number <= 80342?
* true
* Q20: Is your number <= 80341?
* false
*
* Your integer is 80342.
*
*************************************************************************/
public class QuestionsTwenty {
public static void main(String[] args) {
int lo = 0, hi = 1000000;
System.out.println("Think of an integer between " + lo + " and " + hi
+ ".");
System.out.println("Truthfully answer 'true' or 'false' to each
question I ask.");
System.out.println();
for (int i = 1; lo < hi; i++) {

// invariant: number must be in the interval [lo, hi]


int mid = lo + (hi - lo) / 2;
System.out.print("Q" + i + ": ");
System.out.println("Is your number <= " + mid + "?");
boolean response = StdIn.readBoolean();
if (response) hi = mid;
else
lo = mid + 1;

System.out.println("Your integer is " + lo + ".");


System.out.println();

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Add.java

Below is the syntax highlighted version of Add.java from 1.5 Input and Output.

/*************************************************************************
* Compilation: javac Add.java
* Execution:
java Add
* Dependencies: StdIn.java
*
* Prompts the user for two integers numbers, reads them in from standard
* input, and prints out their sum.
*
* Note: you must hav the file StdIn.java in your working directory.
*
* % java Add
* Type the first integer
* 5
<-- user types this
* Type the second integer
* 33
<-- user types this
* Their sum is 38
*
*************************************************************************/
public class Add {
public static void main(String[] args) {
// prompt user for first integer and read from standard input
StdOut.println("Type the first integer");
int x = StdIn.readInt();
// prompt user for second integer and read from standard input
StdOut.println("Type the second integer");
int y = StdIn.readInt();

// compute sum and print to standard output


int sum = x + y;
StdOut.println("Their sum is " + sum);

Copyright 20002010, Robert Sedgewick and Kevin Wayne.


Last updated: Wed Feb 9 09:02:07 EST 2011.

Transition.java

Below is the syntax highlighted version of Transition.java from 1.6 Case Study: PageRank.

/*************************************************************************
* Compilation: javac Transition.java
* Execution:
java Transition < input.txt

* Data files:
http://introcs.cs.princeton.edu/16pagerank/tiny.txt
*
http://introcs.cs.princeton.edu/16pagerank/medium.txt
*
* This program is a filter that reads links from standard input and
* produces the corresponding transition matrix on standard output.
* First, it processes the input to count the outlinks from each page.
* Then it applies the 90-10 rule to compute the transition matrix.
* It assumes that there are no pages that have no outlinks in the
* input (see Exercise 1.6.3).
*
* % more tiny.txt
* 5
* 0 1
* 1 2 1 2
* 1 3 1 3 1 4
* 2 3
* 3 0
* 4 0 4 2
*
* % java Transition < tiny.txt
* 5 5
*
0.02 0.92 0.02 0.02 0.02
*
0.02 0.02 0.38 0.38 0.20
*
0.02 0.02 0.02 0.92 0.02
*
0.92 0.02 0.02 0.02 0.02
*
0.47 0.02 0.47 0.02 0.02
*
*************************************************************************/
public class Transition {
public static void main(String[] args) {
int N = StdIn.readInt();
int[][] counts = new int[N][N];
i to page j
int[] outDegree = new int[N];
i to anywhere

// number of pages
// counts[i][j] = # links from page
// outDegree[i] = # links from page

// Accumulate link counts.


while (!StdIn.isEmpty()) {
int i = StdIn.readInt();
int j = StdIn.readInt();
outDegree[i]++;
counts[i][j]++;
}
StdOut.println(N + " " + N);
// Print probability distribution for row i.
for (int i = 0; i < N; i++) {
// Print probability for column j.
for (int j = 0; j < N; j++) {
double p = .90*counts[i][j]/outDegree[i] + .10/N;

}
}

StdOut.printf("%7.5f ", p);


}
StdOut.println();

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Sun Oct 6 02:26:32 EDT 2013.

RandomSurfer.java

Below is the syntax highlighted version of RandomSurfer.java from 1.6 Case Study: PageRank.

/*************************************************************************
* Compilation: javac RandomSurfer.java
* Execution:
java RandomSurfer T
* Data files:
http://introcs.cs.princeton.edu/16pagerank/tiny.txt
*
http://introcs.cs.princeton.edu/16pagerank/medium.txt
*
* % java Transition < tiny.txt | java RandomSurfer 1000000
*
0.27297 0.26583 0.14598 0.24729 0.06793
*
*************************************************************************/
public class RandomSurfer {
public static void main(String[] args) {
int T = Integer.parseInt(args[0]);
int M = StdIn.readInt();
since M = N
int N = StdIn.readInt();

// number of moves
// number of pages

- ignore

// number of pages

// Read transition matrix.


double[][] p = new double[N][N];
// p[i][j] = prob. that surfer
moves from page i to page j
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
p[i][j] = StdIn.readDouble();
int[] freq = new int[N];
page i
// Start at page 0.
int page = 0;
for (int t = 0; t < T; t++) {
// Make one random move.
double r = Math.random();

// freq[i] = # times surfer hits

double sum = 0.0;


for (int j = 0; j < N; j++) {
// Find interval containing r.
sum += p[page][j];
if (r < sum) { page = j; break; }
}
freq[page]++;

// Print page ranks.


for (int i = 0; i < N; i++) {
StdOut.printf("%8.5f", (double) freq[i] / T);
}
StdOut.println();

Copyright 20002011, Robert Sedgewick and Kevin Wayne.


Last updated: Fri Aug 5 09:26:45 EDT 2011.

You might also like