• Home
  • Textbooks
  • Introduction to Java Programming. Comprehensive Version
  • Developing Efficient Algorithms

Introduction to Java Programming. Comprehensive Version

Y. Daniel Liang

Chapter 22

Developing Efficient Algorithms - all with Video Answers

Educators


Chapter Questions

19:54

Problem 1

(Maximum consecutive increasingly ordered substring) Write a program that prompts the user to enter a string and displays the maximum consecutive increasingly ordered substring. Analyze the time complexity of your program. Here is a sample run:

Nicole Powell
Nicole Powell
Numerade Educator
01:34

Problem 2

(Maximum increasingly ordered subsequence) Write a program that prompts the user to enter a string and displays the maximum increasingly ordered subsequence of characters. Analyze the time complexity of your program. Here is a sample run:

Nick Johnson
Nick Johnson
Numerade Educator
01:45

Problem 3

(Pattern matching) Write a program that prompts the user to enter two strings and tests whether the second string is a substring of the first string. Suppose the neighboring characters in the string are distinct. (Don't use the indexof method in the String class.) Analyze the time complexity of your algorithm. Your algorithm needs to be at least $O(n)$ time. Here is a sample run of the program:

Florencia Cuzmar
Florencia Cuzmar
Numerade Educator
01:45

Problem 4

(Pattern matching) Write a program that prompts the user to enter two strings and tests whether the second string is a substring of the first string. (Don't use the indexof method in the String class.) Analyze the time complexity of your algorithm. Here is a sample run of the program:

Florencia Cuzmar
Florencia Cuzmar
Numerade Educator
02:25

Problem 5

(Same-number subsequence) Write an $O(n)$ program that prompts the user to enter a sequence of integers ending with 0 and finds the longest subsequence with the same number. Here is a sample run of the program:

Nick Johnson
Nick Johnson
Numerade Educator

Problem 6

(Execution time for GCD) Write a program that obtains the execution time for finding the GCD of every two consecutive Fibonacci numbers from the index 40 to index 45 using the algorithms in Listings 22.3 and 22.4. Your program should print a table like this:

Check back soon!
19:32

Problem 7

(Closest pair of points) Section 22.8 introduced an algorithm for finding the closest pair of points using a divide-and-conquer approach. Implement the algorithm to meet the following requirements:
- Define the classes Point and CompareY in the same way as in Programming Exercise 20.4.
- Define a class named Pair with the data fields $\mathrm{p} 1$ and $\mathrm{p} 2$ to represent two points, and a method named getDistance () that returns the distance between the two points.
- Implement the following methods:
$/^{* *}$ Return the distance of the closest pair of points $\# /$ public static Pair getClosestPair(double[] [] points)
$/^{*+}$ Return the distance of the closest pair of points */ public static Pair getClosestPair(Point [] points)
/= Return the distance of the closest pair of points
${ }^*$ in pointsOrderedOnx[1ow..high]. This is a recursive
* method. points0rderedOnX and pointsOrderedOnY are
" not changed in the subsequent recursive calls. \#/
pub1ic static Pair distance(Point[] pointsOrderedOnX, int low, int high, Point[] pointsOrderedOnY)
$/ *$ Compute the distance between two points p1 and p2 \%/ public static double distance(Point p1, Point p2)
$/=$ Compute the distance between points $\left(x_1, y_1\right)$ and $\left(x_2, y_2\right)$ \#/ public static double distance(double $\times 1$, double $y 1$, double $\times 2$, double $y 2$ )

Bryan Lynn
Bryan Lynn
Numerade Educator
06:21

Problem 8

(All prime numbers up to $10,000,000,000$ ) Write a program that finds all prime numbers up to $10,000,000,000$. There are approximately $455,052,511$ such prime numbers. Your program should meet the following requirements:
- Your program should store the prime numbers in a binary data file, named PrimeNumbers.dat. When a new prime number is found, the number is appended to the file.
- To find whether a new number is prime, your program should load the prime numbers from the file to an array of the long type of size 10000. If no number in the array is a divisor for the new number, continue to read the next 10000 prime numbers from the data file, until a divisor is found or all numbers in the file are read. If no divisor is found, the new number is prime.
- Since this program takes a long time to finish, you should run it as a batch job from a UNIX machine. If the machine is shut down and rebooted, your program should resume by using the prime numbers stored in the binary data file rather than start over from scratch.
(Geometry: gift-wrapping algorithm for finding a convex hull) Section 22.10.1 introduced the gift-wrapping algorithm for finding a convex hull for a set of points. Assume that the Java's coordinate system is used for the points. Implement the algorithm using the following method:
/** Return the points that form a convex hull "/ public static ArrayList<Point2D> getConvexHul1(double[] [] s)

Point2D is defined in Section 9.6.
Write a test program that prompts the user to enter the set size and the points and displays the points that form a convex hull. Here is a sample run:

Eric Mockensturm
Eric Mockensturm
Numerade Educator
05:09

Problem 9

(Geometry: gift-wrapping algorithm for finding a convex hull) Section 22.10.1 introduced the gift-wrapping algorithm for finding a convex hull for a set of points. Assume that the Java's coordinate system is used for the points. Implement the algorithm using the following method:
/"t Return the points that form a convex hull "/ public static Arraylist<Point2D> getConvexHull(double [] [] s)
Point2D is defined in Section 9.6.
Write a test program that prompts the user to enter the set size and the points and displays the points that form a convex hull. Here is a sample run:FIGURE CANT COPY

Jordan Gassaway
Jordan Gassaway
Numerade Educator

Problem 10

(Number of prime numbers) Programming Exercise 22.8 stores the prime numbers in a file named PrimeNumbers.dat. Write a program that finds the number of prime numbers that are less than or equal to $10,100,1,000,10,000$, $100,000,1,000,000,10,000,000,100,000,000,1,000,000,000$, and $10,000,000,000$. Your program should read the data from PrimeNumbers.dat.

Check back soon!

Problem 11

(Geometry: Graham's algorithm for finding a convex hull) Section 22.10.2 introduced Graham's algorithm for finding a convex hull for a set of points. Assume that the Java's coordinate system is used for the points. Implement the algorithm using the following method:
/*t Return the points that form a convex hu17 */ public static Arraylist<MyPoint> getConvexHul1(double[][] s)
MyPoint is a static inner class defined as follows:
private static class MyPoint implements Comparable<MyPoint> \{ double $x, y$;
MyPoint rightMostLowestPoint;
MyPoint(double $x$, double $y$ ) \{ \} this. $x=x$; this. $y=y$;
public void setRightMostLowestPoint(MyPoint p) \{ \} rightMostLowestPoint $=p$;
Goverride
public int compareTo(MyPoint o) \{
// Implement it to compare this point with point o
// angularly along the $x$-axis with rightMostlowestPoint $/ /$ as the center, as shown in Figure 22.10b. By implementing // the Comparable interface, you can use the Array.sort // method to sort the potnts to stmplify coding.
\}
\}
Write a test program that prompts the user to enter the set size and the points and displays the points that form a convex hull. Here is a sample run:FIGURE CANT COPY

Check back soon!

Problem 12

(Last 100 prime numbers) Programming Exercise 22.8 stores the prime numbers in a file named PrimeNumbers.dat. Write an efficient program that reads the last 100 numbers in the file, (Hint; Don't read all numbers from the file. Skip all numbers before the last 100 numbers in the file.)

Check back soon!

Problem 13

(Geometry: convex hull animation) Programming Exercise 22.11 finds a convex hull for a set of points entered from the console. Write a program that enables the user to add/remove points by clicking the left/right mouse button, and displays a convex hull, as shown in Figure $22.8 \mathrm{c}$.

Check back soon!

Problem 14

(Execution time for prime numbers) Write a program that obtains the execution time for finding all the prime numbers less than 8,000,000, 10,000,000, $12,000,000,14,000,000,16,000,000$, and $18,000,000$ using the algorithms in Listings 22.5-22.7. Your program should print a table like this:$$
\begin{array}{l|llllll}
& 8000000 & 10000000 & 12000000 & 14000000 & 16000000 & 18000000 \\
\hline \text { Listing 22.5 } & & & & & \\
\text { Listing 22.6 } & & & & & \\
\text { Listing 22.7 } & & & & & \\
& & & &
\end{array}
$$

Check back soon!

Problem 15

(Geometry: non-cross polygon) Write a program that enables the user to add/ remove points by clicking the left/right mouse button, and displays a noncrossed polygon that links all the points, as shown in Figure 22.11 a. A polygon is crossed if two or more sides intersect, as shown in Figure 22.11b. Use the following algorithm to construct a polygon from a set of points.FIGURE CANT COPY
Figure 22.11 (a) Programming Exercise22.15 displays a non-crossed polygon for a set of points. (b) Two or more sides intersect in a crossed polygon.
Step 1: Given a set of points $S$, select the rightmost lowest point $p_0$ in the set $S$.
Step 2: Sort the points in $S$ angularly along the $x$-axis with $p_0$ as the center. If there is a tie and two points have the same angle, the one that is closer to $p_0$ is considered greater. The points in $S$ are now sorted as $p_0, p_1, p_2, \ldots$, $p_{n-1}$.
Step 3: The sorted points form a non-cross polygon.

Check back soon!

Problem 16

(Linear search animation) Write a program that animates the linear search algorithm. Create an array that consists of 20 distinct numbers from 1 to 20 in a random order. The array elements are displayed in a histogram, as shown in Figure 22.12. You need to enter a search key in the text field. Clicking the Step button causes the program to perform one comparison in the algorithm and repaints the histogram with a bar indicating the search position. This button also freezes the text field to prevent its value from being changed. When the algorithm is finished, display the status in the label at the top of the border pane to inform the user. Clicking the Reset button creates a new random array for a new start. This button also makes the text field editable.
FIGURE CANT COPY
Ficure 22.12 The program animates a linear search.

Check back soon!

Problem 17

(Closest-pair animation) Write a program that enables the user to add/remove points by clicking the left/right mouse button, and displays a line that connects the pair of nearest points, as shown in Figure 22.4.

Check back soon!

Problem 18

(Binary search animation) Write a program that animates the binary search algorithm. Create an array with numbers from 1 to 20 in this order. The array elements are displayed in a histogram, as shown in Figure 22.13. You need to enter a search key in the text field. Clicking the Step button causes the program to perform one comparison in the algorithm. Use a light-gray color to paint the bars for the numbers in the current search range and use a black color to paint the a bar indicating the middle number in the search range. The Step button also freezes the text field to prevent its value from being changed. When the algorithm is finished, display the status in a label at the top of a border pane. Clicking the Reset button enables a new search to start. This button also makes the text field editable.
FIGURE CANT COPY
Ficure 22.13 The program animates a binary search.

Check back soon!

Problem 19

(Largest block) The problem for finding a largest block is described in Programming Exercise 8.35. Design a dynamic programming algorithm for solving this problem in $O\left(n^2\right)$ time. Write a test program that displays a 10 -by- 10 square matrix, as shown in Figure 22.14a. Each element in the matrix is 0 or 1, randomly generated with a click of the Refresh button. Display each number centered in a text field. Use a text field for each entry. Allow the user to change the entry value. Click the Find Largest Block button to find a largest square submatrix that consists of 1s. Highlight the numbers in the block, as shown in Figure 22.14b. See www.cs.armstrong.edu/liang/animation/FindL.argestBlock.html for an interactive test.
FIGURE CANT COPY
Ficure 22.14 The program finds the largest block of $1 \mathrm{~s}$.

Check back soon!
16:00

Problem 20

(Game: multiple Sudoku solutions) The complete solution for the Sudoku problem is given in Supplement VI.A. A Sudoku problem may have multiple solutions. Modify Sudoku.java in Supplement VI.A to display the total number of the solutions. Display two solutions if multiple solutions exist.

SO
Sigurður Orri
Numerade Educator

Problem 21

(Game: Sudoku) The complete solution for the Sudoku problem is given in Supplement VI.C. Write a program that lets the user enter the input from the text fields, as shown in Figure 22.15a. Clicking the Solve button displays the result, as shown in Figure $22.15 \mathrm{~b}-\mathrm{c}$.
FIGURE CANT COPY
Ficure 22.15 The program solves the Sudoku problem.

Check back soon!

Problem 22

(Game: recursive Sudoku) Write a recursive solution for the Sudoku problem.

Check back soon!
04:42

Problem 23

(Game: multiple Eight Queens solution) Write a program to display all possible solutions for the Eight Queens puzzle in a scroll pane, as shown in Figure 22.16. For each solution, put a label to denote the solution number. (Hint: Place all solution panes into an HBox and place this one pane into a Scro11Pane.)

Morgan Cheatham
Morgan Cheatham
Numerade Educator

Problem 24

(Find the smallest number) Write a method that uses the divide-and-conquer approach to find the smallest number in a list.
FIGURE CANT COPY
FicurE 22.16 All solutions are placed in a scroll pane.

Check back soon!

Problem 25

(Game: Sudoku) Revise Programming Exercise 22.21 to display all solutions for the Sudoku game, as shown in Figure 22.17a. When you click the Solve button, the program stores all solutions in an ArrayList. Each element in the list is a two-dimensional 9-by-9 grid. If the program has multiple solutions, the Next button appears as shown in Figure 22.17b. You can click the Next button to display the next solution and also a label to show the solution count. When the Clear button is clicked, the cells are cleared and the Next button is hidden as shown in Figure $22.17 \mathrm{c}$.
FIGURE CANT COPY
Ficure 22.17 The program can display multiple Sudoku solutions.

Check back soon!