Vous êtes sur la page 1sur 10

CS210 Study Guide Swami Iyer

1 Programming Model (Algorithms 1.1)


Problems

Problem 1. Consider the following method:


public static int mystery ( int [] a ) {
int x = 0;
for ( int i = 0; i < a . length ; i ++) {
x += a [ i ] * a [ i ];
}
return x ;
}

a. What does mystery() compute and return in general?


b. What will mystery() return if the argument a is an integer array containing the values 1, 2, 3, 4, and 5?

Problem 2. Consider the following method:


public static int [][] mystery ( int n , int k ) {
int [][] a = new int [ n ][ n ];
for ( int i = 0; i < n ; i ++) {
for ( int j = 0; j < n ; j ++) {
a [ i ][ j ] = ( i > j ) ? 0 : k ;
}
}
return a ;
}

a. What does mystery() compute and return in general?


b. What will mystery() return if the arguments are n = 4 and k = 5?

Problem 3. Consider the following recursive method:


public static int mystery ( int a , int b ) {
if ( b == 0) { return 0; }
if ( a == 0) { return mystery ( b - 1 , a ); }
return b + mystery (b , a - 1);
}

a. What will mystery(0, 10) return?


b. What will mystery(10, 3) return?
c. What will mystery(200, 300) return?
d. What does mystery(a, b) return in general about a and b?

Problem 4. Consider the following program:


// Circle . java

import edu . princeton . cs . algs4 . StdOut ;

public class Circle {


public static void main ( String [] args ) {
double r = Double . parseDouble ( args [0]);
double c = 2 * Math . PI * r ;
double a = Math . PI * r * r ;
StdOut . printf (" radius = %.2 f , circumference = %.2 f , area = %.2 f \ n " , r , c , a );
}
}

2 of 29
CS210 Study Guide Swami Iyer

a. What does Circle compute and print in general?


b. What will Circle write when run with the command-line argument 5?

Problem 5. Write a program RandomInts.java that takes command-line arguments n, a, and b as integers and writes n random
integers (one per line) from the range [a, b]. For example
$ java RandomInts 5 100 1000
257
197
670
446
590

Problem 6. Write a program Stats.java that reads integers from standard input, and computes and writes their mean,
variance, and standard deviation, each up to 3 decimal places. For example
$ java Stats
1
2
3
4
5
< ctrl -d >
mean = 3.000 , var = 2.000 , std = 1.414

Problem 7. a. What is the command for generating 10000 random integers from the interval [1, 24] using the RandomInts
program from Problem 5?
b. What is the command for generating 10000 random integers from the interval [1, 24] and saving the output in a file called
numbers.txt?

c. What is the command for using the Stats program from Problem 6 to calculate stats for the numbers in numbers.txt?
d. What is the command to perform the last two tasks in one shot?

Solutions

Solution 1.
a. The sum of squares of the integers in a.
b. 55

Solution 2.
a. An n-by-n matrix in which the elements below the main diagonal are zeros and the rest of the elements are k.
b. {{5, 5, 5, 5}, {0, 5, 5, 5}, {0, 0, 5, 5}, {0, 0, 0, 5}}
Solution 3.

a. 0
b. 30
c. 60000

d. a * b
Solution 4.
a. Reads a command-line argument r as a double, computes the circumference c and area a of a circle with radius r, and
prints the values of r, c, and a up to 2 decimal places.

3 of 29
CS210 Study Guide Swami Iyer

b. radius = 5.00, circumference = 31.42, area = 78.54


Solution 5.
# RandomInts . java

import edu . princeton . cs . algs4 . StdOut ;


import edu . princeton . cs . algs4 . StdRandom ;

public class RandomInts {


public static void main ( String [] args ) {
int n = Integer . parseInt ( args [0]);
int a = Integer . parseInt ( args [1]);
int b = Integer . parseInt ( args [2]);
for ( int i = 0; i < n ; i ++) {
int r = StdRandom . uniform (a , b + 1);
StdOut . println ( r );
}
}
}

Solution 6.
# Stats . java

import edu . princeton . cs . algs4 . StdIn ;


import edu . princeton . cs . algs4 . StdOut ;

public class Stats {


public static void main ( String [] args ) {
int a [] = StdIn . readAllInts ();
double mean = 0.0 , var = 0.0 , std = 0.0;
for ( int x : a ) {
mean += x ;
}
mean /= a . length ;
for ( int x : a ) {
var += ( x - mean ) * ( x - mean );
}
var /= a . length ;
std = Math . pow ( var , 0.5);
StdOut . printf (" mean = %.3 f , var = %.3 f , std = %.3 f \ n " , mean , var , std );
}
}

Solution 7.
a. java RandomInts 10000 1 24
b. java RandomInts 10000 1 24 > numbers.txt
c. java Stats < numbers.txt

d. java RandomInts 10000 1 24 | java Stats

2 Data Abstraction (Algorithms 1.2)


Problems

Problem 1. Implement an immutable and comparable data type Card that represents a playing card. Each card is represented
using an integer rank (0 for 2, 1 for 3, . . . , 11 for King, and 12 for Ace) and an integer suit (0 for Clubs, 1 for Diamonds, 2
for Hearts, and 3 for Spades). Your data type must support the following API:

4 of 29
CS210 Study Guide Swami Iyer

method/class description
Card(int suit, int rank) construct a card given its suit and rank
boolean equals(Card that) is this card the same as that
String toString() a string representation of the card; for example “Ace of Hearts”
int compareTo(Card that) is this card less than† , equal to, or greater than that card
static class SuitOrder a comparator for comparing cards based on their suits
a comparator for comparing cards based on
static class ReverseRankOrder
the reverse order of their ranks

† A card c1 is less than a card c2 if either the suit of c1 is less than the suit of c2 or c1 and c2 are of the same suit and the
denomination of c1 is less than the denomination of c2 . We refer to this as the natural order.

Problem 2. Suppose deck is an array of Card (the data type from Problem 1) objects.

a. Write down a statement that uses Arrays.sort() to sort deck by the natural order.
b. Write down a statement that uses Arrays.sort() to sort deck by suit order.
c. Write down a statement that uses Arrays.sort() to sort deck by reverse rank order.

Problem 3. Complete the implementation of the iterable data type Range that allows clients to iterate over a range of integers
from the interval [lo, hi] in increments specified by step. For example, the following code
for ( int i : new Range (1 , 10 , 3)) {
StdOut . println ( i );
}

should output
1
4
7
10

import java . util . Iterator ;

public class Range implements Iterable < Integer > {


private int lo ;
private int hi ;
private int step ;

// Construct a range given the bounds and the step size .


public Range ( int lo , int hi , int step ) {
...
}

// A range iterator .
public Iterator < Integer > iterator () {
...
}

// Helper range iterator .


private class RangeIterator implements Iterator < Integer > {
private int i ;

public RangeIterator () {
...
}

public boolean hasNext () {


...
}

public Integer next () {


...

5 of 29
CS210 Study Guide Swami Iyer

}
}
}

Solutions

Solution 1.
// Card . java

import java . util . Comparator ;

public class Card implements Comparable < Card > {


private static String [] RANKS = {"2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" ,
"10" , " Jack " , " Queen " , " King " , " Ace "};
private static String [] SUITS = {" Clubs " , " Diamonds " , " Hearts " , " Spades "};
private final int suit ;
private final int rank ;

public Card ( int suit , int rank ) {


this . suit = suit ;
this . rank = rank ;
}

public boolean equals ( Card other ) {


return compareTo ( other ) == 0;
}

public String toString () {


return RANKS [ rank ] + " of " + SUITS [ suit ];
}

public int compareTo ( Card that ) {


if ( suit < that . suit || suit == that . suit && rank < that . rank ) {
return -1;
}
else if ( suit == that . suit && rank == that . rank ) {
return 0;
}
else {
return 1;
}
}

public static class SuitOrder implements Comparator < Card > {


public int compare ( Card c1 , Card c2 ) {
return c1 . suit - c2 . suit ;
}
}

public static class R e v e r s e R a n k O r d e r implements Comparator < Card > {


public int compare ( Card c1 , Card c2 ) {
return c2 . rank - c1 . rank ;
}
}
}

Solution 2.
a. Arrays . sort ( deck );

b. Arrays . sort ( deck , new Card . SuitOrder ());

c. Arrays . sort ( deck , new Card . R e v e r s e R a n k O r d e r ());

6 of 29
CS210 Study Guide Swami Iyer

Solution 3.
// Range . java

import java . util . Iterator ;

public class Range implements Iterable < Integer > {


private int lo ;
private int hi ;
private int step ;

public Range ( int lo , int hi , int step ) {


this . lo = lo ;
this . hi = hi ;
this . step = step ;
}

public Iterator < Integer > iterator () {


return new RangeIterator ();
}

private class RangeIterator implements Iterator < Integer > {


private int i ;

public RangeIterator () {
i = lo ;
}

public boolean hasNext () {


return i <= hi ;
}

public Integer next () {


int r = i ;
i += step ;
return r ;
}
}
}

3 Analysis of Algorithms (Algorithms 1.4)


Problems

Problem 1. Consider an array a[] with 104 integers.

a. Roughly how many comparisons are involved if one performs 106 linear search operations on a?
b. Roughly how many comparisons (sorting and searching included) are involved if one performs 106 binary search operations
on a?

Problem 2. Consider the following table, which gives the running time T (N ) in seconds for a program for various values of
the input size N :

N T (N )
100 3
200 25
400 200
800 1,599

What is the order of growth of T (N )?


Problem 3. Provide the order-of-growth classification (constant, logarithmic, linear, linearithmic, quadratic, cubic, or
exponential) for the following tasks:

7 of 29
CS210 Study Guide Swami Iyer

a. Adding two N -by-N matrices.


b. Enumerating the subsets of a set with N items.
c. Finding the average of N numbers.
d. Finding distinct triples (a, b, c) in a collection of N positive integers such that a2 + b2 = c2 .

e. Finding the maximum key in a maximum-oriented heap-ordered binary tree with N items.
f. Inserting a new key into a heap-ordered binary tree with N items.
g. Multiplying two numbers.

h. Sorting an array of N items using quick sort.


i. Sorting an array of N items using insertion sort.
j. Summing up the diagonal elements of an N -by-N matrix.
Problem 4. Give the order of growth (as
( in a function
Big-O of )N ) of the running times of each of the following code fragments:
notation

a. int sum = 0;
for ( int n = N ; n > 0; n /= 2) {
for ( int i = 0; i < n ; i ++) {
sum ++;
}
}

b. int sum = 0;
for ( int i = 1; i < N ; i *= 2) {
for ( int j = 0; j < i ; j ++) {
sum ++;
}
}

c. int sum = 0;
for ( int i = 1; i < N ; i *= 2) {
for ( int j = 0; j < N ; j ++) {
sum ++;
}
}

Problem 5. Consider a data type Planet with the attributes String name and int moons. What is the memory footprint (in
bytes) of the array planets of Planet objects, created and initialized in the following manner?
Planet [] planets = new Planet [8];
planets [0] = new Planet (" Mercury " , 0);
planets [1] = new Planet (" Venus " , 0);
planets [2] = new Planet (" Earth " , 1);
planets [3] = new Planet (" Mars " , 2);
planets [4] = new Planet (" Jupiter " , 67);
planets [5] = new Planet (" Saturn " , 62);
planets [6] = new Planet (" Uranus " , 27);
planets [7] = new Planet (" Neptune " , 14);

Solutions

Solution 1.
a. 106 · 104 = 1010
b. 106 lg 104 = 13 · 106

8 of 29
CS210 Study Guide Swami Iyer

Solution 2. T (N ) ∼ N 3 (cubic)
Solution 3.
a. Quadratic
b. Exponential
c. Linear
d. Cubic
e. Constant
f. Logarithmic
g. Constant
h. Linearithmic
i. Quadratic
j. Linear
Solution 4.
a. Linear
b. Linear
c. Linearithmic
Solution 5. 24 + 8 × 32 + 56 + 2 × (7 + 5 + 5 + 4 + 7 + 6 + 6 + 7) = 430 bytes

4 Basic Data Structures (Algorithms 1.3)


Problems

Problem 1. Consider the following method:


public static int mystery ( Node < Integer > first ) {
int x = 0;
for ( Node y = first , int i = 0; y != null ; y = y . next , i ++) {
x += ( i % 2 == 0) ? y . item : 0;
}
return x ;
}

a. What does mystery() compute and return in general?


b. What will mystery() return if the argument (a Node object) represents a linked list containing integers 1, 2, 3, . . . , 10?

Problem 2. Consider the following method:


public static int mystery ( Bag < Integer > bag ) {
int x = 0;
Itereator < Integer > iter = bag . iterator ();
while ( iter . hasNext ()) {
x += iter . next ();
}
return x ;
}

a. What does mystery() compute and return in general?

9 of 29
CS210 Study Guide Swami Iyer

b. What will mystery() return if the argument (a Bag object) contains the integers 1, 2, 3, . . . , 10?

Problem 3. Suppose that a minus sign in the input indicates pop the stack and write the return value to standard output,
and any other string indicates push the string onto the stack. Further suppose that following input is processed:
it was - the best - of times - - - it was - the - - worst - of times -

a. What is written to standard output?


b. What are the contents (top to bottom) left on the stack?

Problem 4. Suppose that an intermixed sequence of (stack) push and pop operations are performed. The pushes push the
integers 0 through 9 in order; the pops print out the return value. Which of the following sequence(s) could not occur?
A 4 3 2 1 0 9 8 7 6 5

B 4 6 8 7 5 3 2 9 0 1

C 2 5 6 7 4 8 9 3 1 0

D 4 3 2 1 0 5 6 7 8 9

E 1 2 3 4 5 6 9 8 7 0

F 0 4 6 5 3 8 1 7 2 9

G 1 4 7 9 8 6 5 3 0 2

H 2 1 4 3 6 5 8 7 9 0

Problem 5. Consider the following code fragment:


Stack < Integer > s = new Stack < Integer >();
while ( n > 0) {
s . push ( n % 2);
n = n / 2;
}
while (! s . isEmpty ()) {
StdOut . print ( s . pop ());
}
StdOut . println ();

a. What does the following code fragment print when n is 50?


b. Give a high-level description of what it does when presented with a positive integer n.

Problem 6. Suppose that a minus sign in the input indicates dequeue the queue and write the return value to standard
output, and any other string indicates enqueue the string onto the queue. Further suppose that following input is processed:
it was - the best - of times - - - it was - the - - worst - of times -

a. What is written to standard output?


b. What are the contents (head to tail) left on the queue?

Problem 7. Suppose that a client performs an intermixed sequence of (queue) enqueue and dequeue operations. The enqueue
operations put the integers 0 through 9 in order onto the queue; the dequeue operations print out the return value. Which
of the following sequence(s) could not occur?
A 0 1 2 3 4 5 6 7 8 9

B 4 6 8 7 5 3 2 9 0 1

C 2 5 6 7 4 8 9 3 1 0

D 4 3 2 1 0 5 6 7 8 9

10 of 29
CS210 Study Guide Swami Iyer

Problem 8. What does the following code fragment do to the queue q?


Stack < String > s = new Stack < String >();
while (! q . isEmpty ()) {
s . push ( q . dequeue ());
}
while (! s . isEmpty ()) {
q . enqueue ( s . pop ());
}

Solutions

Solution 1.
a. Computes and returns the sum of every other integer in node, starting at the first.
b. 25
Solution 2.
a. Computes and returns the sum of the integers in bag.
b. 55
Solution 3.
a. was best times of the was the it worst times
b. of it
Solution 4. B, F, and G
Solution 5.
a. 110010
b. Prints the binary representation of n.
Solution 6.
a. it was the best of times it was the worst
b. of times
Solution 7. B, C, and D
Solution 8. Reverses the items on the queue.

5 Union-find (Algorithms 1.5)


Problems

Problem 1. Let’s say we are using the union-find (UF) data structure to solve the dynamic connectivity problem with 10
sites and input pairs (1, 2), (7, 8), (1, 6), (0, 5), (3, 8), (2, 3), (6, 7), (2, 7), and (4, 9), arriving in that order.
a. How many components does UF identify?
b. What are those components?
c. Will the number of components or their membership change if the input pairs arrive in a different order than above?
d. Suppose we process the pairs using QuickFindUF. What are the values in the id array after all the pairs are processed?
e. Suppose we process the pairs using QuickUnionUF. What are the values in the parent array after all the pairs are processed?

11 of 29

Vous aimerez peut-être aussi