Você está na página 1de 17

Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 1

Review Exercises

R17.1

Recursion
Recursion is the idea that you solve a problem by using the solution of the same problem with
simpler inputs.

Iteration
Iteration is using some form of a loop (for loop, while loop) to solve a problem.

Infinite recursion
Infinite recursion is when the recursion never stops. A method calls itself over and over again
with no end in sight.

Indirect recursion
Indirect recursion is the idea of having a method use a helper method to do the recursion.

R17.3

If the array has no elements or only one element, you are done.

Otherwise, first find the smallest element in the array. After obtaining the smallest number, swap
that number with the first element in the array and recursively sort the remaining numbers in the
array.

R17.5

We'll show that the algorithm has the following property:

It transforms a sequence of the form

(any elements) | (ascending sequence)

into

(any elements) | (reversed sequence)


Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 2
going through all the permutations of the tail sequence

For example, if the algorithm is launched on the sequence

2|134

then it transforms it in 5 steps to the sequence

2|431

Let us prove this by induction. It is clear that the algorithm does just that when the length of the
ascending tail sequence is 2.

Now suppose we have a ascending tail sequence, like this:

a0 ... ak ... an-1

where ak < ak+1 < ... < an-1.

By induction, the algorithm first permutes the shorter tail sequence ak+1 ... an-1 until it is
completely reversed to

a0 ... ak an-1 ... ak+1.

Now the algorithm picks the smallest element larger than ak and swaps it (which keeps the tail
sequence descending) and then reverses the tail which makes it ascending. Again, by the
inductive assumption, the shorter tail sequence is now being subjected to all of its permutations
until it is reversed.

To complete the argument, observe that after each reversal of the shorter tail a larger element is
extracted from the shorter tail. Ultimately, the largest element is extracted and the shorter tail is
reversed one last time, leading to the reversal of the longer tail.

R17.7

0! = 1

n! = n * (n-1)!

R17.9
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 3
n
X = 2 - 1, where X is the number of moves required and n is the number of discs to be moved.

Programming Exercises

P17.1
Sentence.java
/**
Reverse a sentence.
*/
public class Sentence
{
/**
Creates a Sentence object.
@param aPhrase a sentence to reverse.
*/
public Sentence(String aPhrase)
{
phrase = aPhrase;
}

/**
Reverses a sentence.
@return the reversed sentence
*/
public String reverse()
{
char c;
String rest;
if (!phrase.equals(""))
{
c = phrase.charAt(0);
rest = phrase.substring(1);
tailSentence = new Sentence(rest);
phrase = tailSentence.reverse() + c;
}
return phrase;
}

/**
Gets the sentence.
@return the sentence
*/
public String getText()
{
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 4
return phrase;
}

private String phrase;


private Sentence tailSentence;
}

ExP17_1.java
/**
A test class for Sentence.
*/
public class ExP17_1
{
public static void main(String[] args)
{
Sentence greeting = new Sentence("Hello!");
greeting.reverse();
System.out.println(greeting.getText());
}
}

P17.3
Sentence.java
/**
A sentence of words.
*/
public class Sentence
{
/**
Construct a Sentence object.
@param aPhrase the phrase entered by user
*/
public Sentence(String aPhrase)
{
phrase = aPhrase;
newPhrase = "";
}

/**
Reverses a string.
*/
public void reverse()
{
for (int i = phrase.length() - 1; i >= 0; i--)
{
char word = phrase.charAt(i);
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 5
newPhrase += word;
}
}

/**
Gets the phrase.
@return the phrase
*/
public String getText()
{
return newPhrase;
}

private String phrase;


private String newPhrase;
}

ExP17_3.java
/**
A test driver for Sentence.
*/
public class ExP17_3
{
public static void main(String[] args)
{
Sentence greeting = new Sentence("Hello!");
greeting.reverse();
System.out.println(greeting.getText());
}
}

P17.5
Sentence.java
/**
A class to find a phrase in a sentence.
*/
public class Sentence
{
/**
Construct a Sentence object.
@param aPhrase the sentence
*/
public Sentence(String aPhrase)
{
phrase = aPhrase;
}
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 6

/**
Finds a string of text in a sentence.
@param text the string to find.
@return true if the string is found, false otherwise

*/
public boolean find(String text)
{
return find_helper(text, 0);
}

/**
Helper method to find the index of a string.
@param text the string to find
@param index the starting index to search
@return true if the string found at or after index
*/
private boolean find_helper(String text, int index)
{
if (phrase.length() < text.length() - index) return false;
if (phrase.substring(index).startsWith(text)) return true;
return find_helper(text, index + 1);
}

private String phrase;


}

ExP17_5.java
/**
A test class for Sentence.
*/
public class ExP17_5
{
public static void main(String[] args)
{
Sentence s = new Sentence("Mississippi!");
int n = s.find("sip");
System.out.println(n);
}
}

P17.7
DataSet.java
/**
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 7
Computes the sum of a set of data values.
*/
public class DataSet
{
/**
Constructs a DataSet object.
@param anArray the set of data values
*/
public DataSet(int[] anArray)
{
array = anArray;
}

/**
Gets the sum in the set of data values
@return the sum of the values in the set
*/
public int getSum()
{
return computeSum(array, array.length);
}

/**
Private method to compute the sum of an array.
@param a the array to compute
@param size the size of the array
@return the sum of the array
*/
private int computeSum(int a[], int size)
{
if (size == 0)
return 0;
else
return a[size - 1] + computeSum(a, size - 1);
}

private int[] array;


}

ExP17_7.java
import java.util.Random;

/**
A test class for DataSet.
*/
public class ExP17_7
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 8
{
public static void main(String[] args)
{
Random generator = new Random();
int capacity = 10;
int[] array = new int[capacity];
for (int i = 0; i < array.length; i++)
{
int num = generator.nextInt(10);
array[i] = num;
System.out.print(array[i] + " ");
}
System.out.println();
DataSet d = new DataSet(array);
System.out.println("Sum=" + d.getSum());
}
}

P17.9
SubstringGenerator.java
/**
This class generates substring permutations of a word.
*/
public class SubstringGenerator
{
/**
Constructs a permutation generator.
@param aWord the word to permute
*/
public SubstringGenerator(String aWord)
{
word = aWord;
current = 0;
if (word.length() > 0)
tailGenerator = new
SubstringGenerator(word.substring(1));
}

public String nextSubstring()


{
current++;
if (word.length() == 0)
{
return "";
}
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 9
String r;
if (current <= word.length())
return word.substring(0, current);
else
return tailGenerator.nextSubstring();
}

public boolean hasMoreSubstrings()


{
return current <= word.length() || tailGenerator != null &&
tailGenerator.hasMoreSubstrings();
}

private String word;


private int current;
private SubstringGenerator tailGenerator;
private String tail;
boolean addedFirst;
}

ExP17_9.java
/**
This program tests the substring generator.
*/
public class ExP17_9
{
public static void main(String[] args)
{
SubstringGenerator generator
= new SubstringGenerator("rum");
System.out.println("---");
while (generator.hasMoreSubstrings())
System.out.println(generator.nextSubstring());
System.out.println("---");
}
}

P17.11
NumberPermutationGenerator.java
public class NumberPermutationGenerator
{
public NumberPermutationGenerator(int n)
{
a = new int[n];
for (int i = 0; i < n; i++)
a[i] = i;
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 10
}

public int[] nextPermutation()


{
if (a.length <= 1) return a;
for (int i = a.length - 1; i > 0; i--)
{
if (a[i - 1] < a[i])
{
int j = a.length - 1;
while (a[i - 1] > a[j])
j--;
swap(i - 1, j);
reverse(i, a.length - 1);
return a;
}
}
return a;
}

public boolean hasMorePermutations()


{
if (a.length <= 1) return false;
for (int i = a.length - 1; i > 0; i--)
{
if (a[i - 1] < a[i])
return true;
}
return false;
}

public void swap(int i, int j)


{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}

public void reverse(int i, int j)


{
while (i < j)
{
swap(i, j);
i++;
j--;
}
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 11
}

private int[] a;
private boolean done;
}

PermutationGenerator.java
public class PermutationGenerator
{
public PermutationGenerator(String aWord)
{
word = aWord;
indexPermutationGenerator
= new NumberPermutationGenerator(word.length());
}

public boolean hasMorePermutations()


{
return indexPermutationGenerator.hasMorePermutations();
}

public String nextPermutation()


{
int[] a = indexPermutationGenerator.nextPermutation();
String r = "";
for (int i = 0; i < a.length; i++)
r = r + word.charAt(a[i]);
return r;
}

private String word;


private NumberPermutationGenerator indexPermutationGenerator;
}

ExP17_11.java
public class ExP17_11
{
public static void main(String[] args)
{
PermutationGenerator generator = new
PermutationGenerator("rum");
while (generator.hasMorePermutations())
System.out.println(generator.nextPermutation());
}
}
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 12
P17.13
DiskMover.java
public class DiskMover
{
public DiskMover(int src, int dest, int dsk)
{
source = src;
target = dest;
disks = dsk;
int other = 6 - source - target;
if (disks > 1)
mover = new DiskMover(source, other, disks - 1);
state = BEFORE_LARGEST;
}

public boolean hasMoreMoves()


{
return state != DONE;
}

public int[] nextMove()


{
if (disks == 1)
{
state = DONE;
return new int[] { source, target };
}

if (state == LARGEST)
{
state = AFTER_LARGEST;
int other = 6 - source - target;
mover = new DiskMover(other, target, disks - 1);
return new int[] { source, target };
}

int[] r = mover.nextMove();

if (!mover.hasMoreMoves())
{
if (state == BEFORE_LARGEST)
state = LARGEST;
else
state = DONE;
}
return r;
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 13
}

private int source;


private int target;
private int disks;
private DiskMover mover;
private int state;

private static final int BEFORE_LARGEST = 1;


private static final int LARGEST = 2;
private static final int AFTER_LARGEST = 3;
private static final int DONE = 4;
}

Tower.java
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;

public class Tower


{
public Tower(Rectangle b)
{
disks = new ArrayList();
bounds = b;
}

public void addDisk(Rectangle d)


{
disks.add(d);
}

public Rectangle removeDisk()


{
return (Rectangle)disks.remove(disks.size() - 1);
}

public void draw(Graphics2D g2)


{
double height = 0;
g2.draw(bounds);
for (int i = 0; i < disks.size(); i++)
{
Rectangle r = (Rectangle)disks.get(i);
r.translate((int)(bounds.getCenterX() - r.getCenterX()),
(int)(bounds.getMaxY() - height - r.getMaxY()));
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 14
g2.fill(r);
height += r.getHeight();
}
}

private ArrayList disks;


private Rectangle bounds;
}

ExP17_13Frame.java
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**

*/
public class ExP17_13Frame extends JFrame
{
/**
Constructs the frame
*/
public ExP17_13Frame()
{
setSize(FRAME_WIDTH, FRAME_HEIGHT);
towerPanel = new ExP17_13Panel(4);

getContentPane().add(
towerPanel, BorderLayout.CENTER);

createControlPanel();
}

/**
Creates the control panel.
*/
public void createControlPanel()
{
JButton nextButton = new JButton("Next");
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 15
class NextButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
towerPanel.drawNextMove();
}
}

nextButton.addActionListener(new NextButtonListener());

// fill content pane

JPanel southPanel = new JPanel();

southPanel.add(nextButton);

getContentPane().add(southPanel, BorderLayout.SOUTH);
}

private ExP17_13Panel towerPanel;

private static final int FRAME_WIDTH = 400;


private static final int FRAME_HEIGHT = 200;
}

ExP17_13Panel.java
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JPanel;

public class ExP17_13Panel extends JPanel


{
/**

*/
public ExP17_13Panel(int n)
{
towers = new Tower[3];
mover = new DiskMover(1, 3, n);
for (int i = 0; i < towers.length; i++)
towers[i] = new Tower(new Rectangle(
i * n * SMALLEST_DISK_WIDTH + n *
SMALLEST_DISK_WIDTH / 2 + i * GAP,
0,
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 16
n * SMALLEST_DISK_WIDTH,
n * DISK_HEIGHT));
for (int i = n; i >= 1; i--)
towers[0].addDisk(new Rectangle(0, 0, i *
SMALLEST_DISK_WIDTH, DISK_HEIGHT));
}

/**
Draws the graphics context
@param g the graphics context
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (int i = 0; i < towers.length; i++)
towers[i].draw(g2);
}

public void drawNextMove()


{
if (!mover.hasMoreMoves()) return;
int[] move = mover.nextMove();
towers[move[1] - 1].addDisk(towers[move[0] -
1].removeDisk());
repaint();
}

private DiskMover mover;


private Tower[] towers;

private static final int SMALLEST_DISK_WIDTH = 20;


private static final int DISK_HEIGHT = 10;
private static final int GAP = 20;
}

ExP17_13.java
import javax.swing.JFrame;

public class ExP17_13


{
public static void main(String[] args)
{
JFrame appFrame = new ExP17_13Frame();
appFrame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
Solutions Manual: Chapter 1 Big Java, by Cay Horstmann 17
appFrame.setTitle("ExP17_13");
appFrame.show();
}
}

Você também pode gostar