Module 8

Ace your homework & exams now with Quizwiz!

A palindrome is a string that reads the same forwards or backwards; for example dad, mom, deed (i.e., reversing a palindrome produces the same string).Write a recursive, boolean-valued method, isPalindrome that accepts a String and returns whether the string is a palindrome.A string, s, is a palindrome if: s is the empty string or s consists of a single letter (which reads the same back or forward), or the first and last characters of s are the same, and the rest of the string (i.e., the second through next-to-last characters) form a palindrome.

boolean isPalindrome(String s) { if (s.length() <= 1) return true; return s.charAt(0) == s.charAt(s.length() - 1) && isPalindrome(s.substring(1, s.length() - 1)); }

18.2.6 Write a recursive mathematical definition for computing 1 + 2 + 3 + ... + n for a positive integer n.

f(n) = 1 if n = 1 f(n) = f(n-1) + n for (n > 1)

The sum of the elements of an int array recursively calculated as follows: The sum of an array of size 0 is 0; Otherwise, the sum of the first n elements of an array is the sum of the last of these added to the sum of the previous n-1 elements. Write an int method named sum that accepts an int array, and the number of elements in the array and returns the sum of the elements of the array.

public static int sum(int[] list, int len){ if (len == 0) return 0; else return list[len - 1] + sum(list, len - 1); }

18.2.2 How many times is the factorial method in Listing 18.1 invoked for factorial(6)?

six times. (base case factorial(0))

How many times is the moveDisks method in Listing 18.8 invoked for moveDisks(5, 'A', 'B', 'C')?

2^5 - 1

How many times is the factorial method in Listing 18.1 invoked for factorial(5)?

D. 6

Analyze the following recursive method. public static long factorial(int n) {return n * factorial(n - 1);}

E. The method runs infinitely and causes a StackOverflowError.

18.9.1 Which of the following statements are true?a. Any recursive method can be converted into a nonrecursive method.b. Recursive methods take more time and memory to execute than nonrecursive methods.c. Recursive methods are always simpler than nonrecursive methods.d. There is always a selection statement in a recursive method to check whether a base case is reached.

a. (TRUE) b. (TRUE) c. (FALSE) d. (TRUE)

18.10.2 Rewrite the fib method in Listing 18.2 using tail recursion.

/** Return the Fibonacci number for the specified index */ public static long fib(long index) { return fib(index, 1, 0); } /** Auxiliary tail-recursive method for fib */ private static int fib(long index, int next, int result) { if (index == 0) return result; else return fib(index - 1, next + result, next); }

What is the output of the following code? public class Test { public static void main(String[] args) { System.out.println(m(4)); } public static int m(int r) { return r > 2 ? r * m(r - 1) : r; } }

24

18.2.1 What is a recursive method? What is an infinite recursion?

A recursive method is the one that calls itself. An infinite recursion is the one that never stops.

Show the output of the following code public class Test1 {public static void main(String[] args) {System.out.println(f2(2, 0));}public static int f2(int n, int result) {if (n == 0)return 0;elsereturn f2(n - 1, n + result);}}

A. 0

How many times is the fib method in Listing 18.2 invoked for fib(5)?

B. 15 Explanation: Hint: number of time fib is invoked in fib(5) = 1 + number of time fib is invoked in fib(3) + number of time fib is invoked in fib(4) = 1 + 5 + 9 = 15

How many times is the recursive moveDisks method invoked for 3 disks?

B. 7

Analyze the following functions; public class Test1 {public static void main(String[] args) {System.out.println(f1(3));System.out.println(f2(3, 0));}public static int f1(int n) {if (n == 0)return 0;else {return n + f1(n - 1);}}public static int f2(int n, int result) {if (n == 0)return result;elsereturn f2(n - 1, n + result);}}

B. f2 is tail recursion, but f1 is not

What is the return value for xMethod(4) after calling the following method? static int xMethod(int n) {if (n == 1)return 1;elsereturn n + xMethod(n - 1);}

C. 10 Explanation: 4 + 3 + 2 + 1 = 10

How many times is the recursive moveDisks method invoked for 4 disks?

C. 15

Fill in the code to complete the following method for computing a Fibonacci number. public static long fib(long index) {if (index == 0) // Base casereturn 0;else if (index == 1) // Base casereturn 1;else // Reduction and recursive callsreturn __________________;}

C. fib(index - 1) + fib(index - 2) D. fib(index - 2) + fib(index - 1)

Fill in the code to complete the following method for computing factorial. /** Return the factorial for a specified index */public static long factorial(int n) {if (n == 0) // Base casereturn 1;elsereturn _____________; // Recursive call}

C. n * factorial(n - 1) D. factorial(n - 1) * n

Fill in the code to complete the following method for sorting a list. public static void sort(double[] list) {___________________________;}public static void sort(double[] list, int high) {if (high > 1) {// Find the largest number and its indexint indexOfMax = 0;double max = list[0];for (int i = 1; i <= high; i++) {if (list[i] > max) {max = list[i];indexOfMax = i;}}// Swap the largest with the last number in the listlist[indexOfMax] = list[high];list[high] = max;// Sort the remaining listsort(list, high - 1);}}

C. sort(list, list.length - 1)

Analyze the following two programs: A:public class Test { public static void main(String[] args) {xMethod(5);}public static void xMethod(int length) {if (length > 1) {System.out.print((length - 1) + " ");xMethod(length - 1);}}}B:public class Test { public static void main(String[] args) {xMethod(5);}public static void xMethod(int length) {while (length > 1) {System.out.print((length - 1) + " ");xMethod(length - 1);}}}

E. Program A produces the output 4 3 2 1 and Program B prints 4 3 2 1 1 1 .... 1 infinitely. Explanation: In Program B, xmethod(5) invokes xmethod(4), xmethod(4) invokes xmethod(3), xmethod(3) invokes xmethod(2), xmethod(2) invokes xmethod(1), xmethod(1) returns control to xmethod(2), xmethod(2) invokes xmethod(1) because of the while loop. This continues infinitely.

18.6.5 Will the program work if line 20 is replaced by the following code?for (int i = 0; i < files.length; i++)

No. The directory may be empty.

18.6.6 Will the program work if lines 20-21 is replaced by the following code?for (File file: files) size += getSize(file); // Recursive call

No. files may be null.

Show the call stack for isPalindrome("abcba") using the method defined in Listing 18.3.

Omitted

Show the call stack for isPalindrome("abcba") using the method defined in Listing 18.4.

Omitted

Show the call stack for selectionSort(new double[]{2, 3, 5, 1}) using the method defined in Listing 18.5.

Omitted

Describe the characteristics of recursive methods.

One or more base cases (the simplest case) are used to stop recursion. Every recursive call reduces the original problem, bringing it increasingly close to a base case until it becomes that case.

is a recursive method that is used to help derive a solution for the original method.

Recursive Helper Method

is a method that directly or indirectly invokes itself.

Recursive Method

18.8.5 Instead of drawing a triangle using a polygon, rewrite the code to draw a triangle by drawing three lines to connect the points in lines 71-77.

Replace lines 71-77 with the following code: // Draw a triangle to connect three points Line line1 = new Line(p1.getX(), p1.getY(), p2.getX(), p2.getY()); Line line2 = new Line(p2.getX(), p2.getY(), p3.getX(), p3.getY()); Line line3 = new Line(p3.getX(), p3.getY(), p1.getX(), p1.getY()); this.getChildren().addAll(line1, line2, line3);

The nth harmonic number is defined non-recursively as: 1 +1/2 + 1/3 + 1/4 + ... + 1/n.Come up with a recursive definition and use it to guide you to write a method named harmonic that accepts an int parameter n and recursively calculates and returns the nth harmonic number as a double.

double harmonic(int n) { return n == 1 ? 1.0 : (1.0 / ((double)n) ) + harmonic(n - 1); }

18.2.4 Write a recursive mathematical definition for computing 2 n for a positive integer n.

f(n) = 2 if n = 1 f(n) = 2 * 2^(n-1) for (n > 1)

18.2.5 Write a recursive mathematical definition for computing x n for a positive integer n and a real number x.

f(n) = x if n = 1 f(n) = x * x^(n-1) for (n > 1)

18.3.1 Show the output of the following two programs:(a) public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int n) { if (n > 0) { System.out.print(n + " "); xMethod(n - 1); } } } (b) public class Test { public static void main(String[] args) { xMethod(5); } public static void xMethod(int n) { if (n > 0) { xMethod(n - 1); System.out.print(n + " "); } } }

(a) The output is 5 4 3 2 1 (b) The output is 1 2 3 4 5

means that a method directly invokes itself recursively.

Direct Recursion

18.9.2 What is a cause for a stack-overflow exception?

When a method is invoked, its contents are placed into a stack. If a method is recursively invoked, it is possible that the stack space is exhausted. This causes stack overflow.

occurs when method A invokes method B, which in turn directly or indirectly invokes method A.

Indirect Recursion

occurs when a recursion does not reduce the problem in a manner that allows it to eventually converge into the base case or a base case is not specified.

Infinite Recursion

is a recursive method that has no pending operations to be performed on return from a recursive call.

Tail Recursion

Which of the following statements are true?

The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two numbers in the series.

18.8.2 What is the base case for the displayTriangles method?

The base case for the displayTriangles method is order == 0.

18.6.1 What is the base case for the getSize method?

The base case for the getSize(File d) method is that d is a file.

For the isPalindrome method in Listing 18.3, what are the base cases? How many times is this method called when invoking isPalindrome("abdxcxdba")?

The base cases are (1) s.length() <= 1 and (2) s.charAt(0) != s.charAt(s.length - 1)When invoking isPalindrome("abdxcxdba"), the isPalindrome method is called 5 times.

How many times is the displayTriangles method invoked for a Sierpinski triangle of order 0, order 1, order 2, and order n?

The displayTriangles method is invoked one time for order 1, 4 times for order 1, 1 + 3 * 3 times for order 2, and 1 + 3^n for order n.

18.10.1 Identify tail-recursive methods in this chapter.

The isPalindrome method in Listing 18.4, sort method in Listing 18.5, and binarySearch method in Listing 18.6 are tail-recursive.

18.8.1 How do you obtain the midpoint between two points?

The midpoint between p1 and p2 is ((p1.x + p2.x)/2, (p1.y + p2.y)/2), which can be obtained by invoking p1.midpoint(p2).

Analyze the following code: public class Test {public static void main(String[] args) {int[] x = {1, 2, 3, 4, 5};xMethod(x, 5);}public static void xMethod(int[] x, int length) {System.out.print(" " + x[length - 1]);xMethod(x, length - 1);}}

The program displays 5 4 3 2 1 and then raises an ArrayIndexOutOfBoundsException. Explanation: xMethod(x, 5) is invoked, then xMethod(x, 4), xMethod(x, 3), xMethod(x, 2), xMethod(x, 1), xMethod(x, 0). When invoking xMethod(x, 0), a runtime exception is raised because System.out.print(' '+x[0-1]) causes array out of bound.

18.6.2 How does the program get all files and directories under a given directory?

The program gets all files and directories under the directory d using d.listFiles(), which returns an array of File objects under the directory.

18.2.3 Show the output of the following programs and identify base cases and recursive calls. (a) public class Test { public static void main(String[] args) { System.out.println( "Sum is " + xMethod(5)); } public static int xMethod(int n) { if (n == 1) return 1; else return n + xMethod(n - 1); } } (b) public class Test { public static void main(String[] args) { xMethod(1234567); } public static void xMethod(int n) { if (n > 0) { System.out.print(n % 10); xMethod(n / 10); } } }

(a) Sum is 15 (5 + 4 + 3 + 2 + 1 = 15)(b) 7654321

18.3.2 What is wrong in the following method?(a) public class Test { public static void main(String[] args) { xMethod(1234567); } public static void xMethod(double n) { if (n != 0) { System.out.print(n); xMethod(n / 10); } } } (b) public class Test { public static void main(String[] args) { Test test = new Test(); System.out.println(test.toString()); } public Test() { Test test = new Test(); } }

(a) n is double. There is no guarantee that n != 0 will be eventually false.( b) Infinite recursion due to new Test() inside the constructor Test().

Fill in the code to complete the following method for checking whether a string is a palindrome. public static boolean isPalindrome(String s) {if (s.length() <= 1) // Base casereturn true;else if _____________________________return false;elsereturn isPalindrome(s.substring(1, s.length() - 1));}

(s.charAt(0) != s.charAt(s.length() - 1)) // Base case

18.3.3 How many times is the fib method in Listing 18.2 invoked for fib(6)?

25 times (Why? number of time fib is invoked in fib(0) =1number of time fib is invoked in fib(1) =1number of time fib is invoked in fib(2) =1+ number of time fib is invoked in fib(1)+number of time fib is invoked in fib(2) =1+1+1=3number of time fib is invoked in fib(3) =1+ number of time fib is invoked in fib(1)+number of time fib is invoked in fib(2) = 1+1+3=5number of time fib is invoked in fib(4) =1+ number of time fib is invoked in fib(2)+number of time fib is invoked in fib(3) = 1+3+5=9number of time fib is invoked in fib(5) =1+ number of time fib is invoked in fib(3)+number of time fib is invoked in fib(4) = 1+5+9=15number of time fib is invoked in fib(6) =1+ number of time fib is invoked in fib(4)+number of time fib is invoked in fib(5) = 1+9+15=25

What is the output of the following code? public class Test { public static void main(String[] args) { m(4); } public static void m(int r) { if (r > 2) { System.out.print(r + " "); m(r - 1); } } }

4 3

Check4 318.3What is the output of the following code?public class Test { public static void main(String[] args) { m(4); } public static void m(int r) { if (r >= 2) { System.out.print(r + " "); m(r - 1); } } }

4 3 2

18.6.3 How many times will the getSize method be invoked for a directory if the directory has three subdirectories and each subdirectory has four files?

4 times for the directories and 4 * 4 time for all the files. So, the total is 20.

Which of the following statements are true?

A. Every recursive method must have a base case or a stopping condition. B. Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. C. Infinite recursion can occur if recursion does not reduce the problem in a manner that allows it to eventually converge into the base case.

In the following method, what is the base case? static int xMethod(int n) {if (n == 1)return 1;elsereturn n + xMethod(n - 1);}

A. n is 1.

What is a recursive helper method?

An overloaded method with additional parameters.

What are the base cases in the following recursive method? public static void xMethod(int n) {if (n > 0) {System.out.print(n % 10);xMethod(n / 10);}}

B. n <= 0

is the simple case on which the problem can be solved immediately. It is also called stopping condition.

Base Case

Fill in the code to complete the following method for binary search. public static int recursiveBinarySearch(int[] list, int key) {int low = 0;int high = list.length - 1;return __________________________;}public static int recursiveBinarySearch(int[] list, int key,int low, int high) {if (low > high) // The list has been exhausted without a matchreturn -low - 1; // Return -insertion point - 1int mid = (low + high) / 2;if (key < list[mid])return recursiveBinarySearch(list, key, low, mid - 1);else if (key == list[mid])return mid;elsereturn recursiveBinarySearch(list, key, mid + 1, high);}

D. recursiveBinarySearch(list, key, low, high)

Fill in the code to complete the following method for checking whether a string is a palindrome. public static boolean isPalindrome(String s) {return isPalindrome(s, 0, s.length() - 1);}public static boolean isPalindrome(String s, int low, int high) {if (high <= low) // Base casereturn true;else if (s.charAt(low) != s.charAt(high)) // Base casereturn false;elsereturn _______________________________;}

E. isPalindrome(s, low + 1, high - 1)

18.8.4 What happens if you enter a negative order? How do you fix this problem in the code?

Will be an infinite loop. To fix it, add if (order < 0) return in the beginning of the method displayTriangle.

18.6.4 Will the program work if the directory is empty (i.e., it does not contain any files)?

Yes.

The Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, has as its first 2 values, 0 and 1; each successive value is then calculated as the sum of the previous two values.The first element in the series is the 0'th element, thus the value 8 is element 6 of the series.The n'th element of the series, written as fib(n), is thus defined as: n if n = 0 or n = 1 fib(n-1) + fib(n-2) Write the int-valued method fib, that takes a single int parameter (say n), and recursively calculates and then returns the n'th element of the Fibonacci series.

int fib(int n) { return n <= 1 ? n : fib(n - 1) + fib(n - 2); }

Given non-negative integers x and n, x taken to the nth power can be defined as: x to the 0th power is 1 x to the nth power can be obtained by multiplying x to the n-1'th power with x Write a method named power that accepts two int parameters x and n (in that order) and recursively calculates and returns the value of x taken to the n'th power. The method returns a long value.

int power(int x, int n) { return n == 0 ? 1 : x * power(x, n - 1); }

Write a method called fact that recursively calculates the factorial value of its single int parameter. The value returned by fact is a long.

long fact(int n) { return n == 0 ? 1 : n * fact(n - 1); }

Write a method called makeLine. The method receives an int parameter that is guaranteed not to be negative and a character. The method returns a String whose length equals the parameter and contains no characters other than the character passed.Thus, makeLine(5,':') will return ::::: (5 colons).The method must not use a loop of any kind (for, while, do-while) nor use any String methods other than concatenation. Instead, it gets the job done by examining its parameter, and if zero returns an empty string otherwise returns the concatenation of the specified character with the string returned by an appropriately formulated recursive call to itself.

public static String makeLine(int x, char c) { if (x <= 0) return ""; else return c + makeLine(x - 1, c); }

Write a method called makeStars. The method receives an int parameter that is guaranteed not to be negative. The method returns a String whose length equals the parameter and contains no characters other than asterisks.Thus, makeStars(8) will return ******** (8 asterisks).The method must not use a loop of any kind (for, while, do-while) nor use any String methods other than concatenation. Instead, it gets the job done by examining its parameter, and if zero returns an empty string otherwise returns the concatenation of an asterisk with the string returned by an appropriately formulated recursive call to itself.

public static String makeStars(int x) { if (x <= 0) return ""; else return "*" + makeStars(x - 1); }

Write the definition of a method named add that receives a reference to a Scanner object associated with a stream of input consisting of integers only. The method reads all the integers remaining to be read from the stream and returns their sum.So if the input were 3 51 204 17 1040, the returned value would be 1315.The method must not use a loop of any kind (for, while, do-while) to accomplish its job.

public static int add(Scanner in) { if (!in.hasNextInt()) return 0; else { int n = in.nextInt(); return n + add(in); } }

Without using a division or multiplication operator and without using iteration, define a recursive method int product that accepts two int parameters, m and k, and calculates and returns the product of m times k. You can count on m>=0 and k>=0.

public static int product(int x, int y) { if (y == 0) return 0; else return x + product(x, y - 1); }

Consider a simple form of integer division: m / k where we are guaranteed that m>=0 and k>0. This can be computed as follows The quotient is 0 when k is greater than m. Otherwise, the quotient is one more than (m-k) / k Write an int-method named quotient that accepts two int parameters, m and k, and recursively calculates and returns the integer quotient of m/k. You can count on m>=0 and k>0. Do not use a division operator here!

public static int quotient(int x, int y) { if (y > x) return 0; else return 1 + quotient(x - y, y); }

The sum of the numbers from 1 to n can be defined recursively as follows: The sum from 1 to 1 is 1. The sum from 1 to n is n plus the sum from 1 to n-1. Write a method namedsumthat accepts anintparameter,n, and recursively calculates and returns the sum of the numbers from1ton.

public static int sum(int n) { if (n == 1) return 1; else return n + sum(n - 1); }

Assume the availability of a method named printStars that can be passed a non-negative integer n and print a line of n asterisks.Write a method named printTriangle that receives a non-negative integer n and prints a triangle of asterisks as follows:first a line of 1 asterisk, followed by a line of 2 asterisks, and then a line of 3 asterisks, and so on and finally a line of n asterisks.For example, if the method received 5 it would print:** ** * ** * * ** * * * *The method must not use a loop of any kind (for, while, do-while) to accomplish its job. The method should invoke printStars to accomplish the task of printing a single line.

public static int sum(int[] list, int len){ if (len == 0) return 0; else return list[len - 1] + sum(list, len - 1); }

The "odd/even factorial" of a positive integer n is represented as n !! and is defined non-recursively as: (n)(n-2)(n-4)...(4)(2) if n is even and is (n)(n-2)(n-4)...(5)(3)(1) if n is odd. For example 7!! equals 7*5*3*1 or 105 and 6!! equals 6*4*2 or 48. Come up with a recursive definition for n!! and use it to guide you to write a method definition for a method called oddevenfact that recursively calculates the odd/even factorial value of its single int parameter. The value returned by oddevenfact is a long.

public static long oddevenfact(int n) { if (n == 1 || n == 0) { return 1; } else { return n * oddevenfact(n - 2); } }

Assume the availability of a method named makeStars that can be passed a non-negative integer n and that returns a String of n asterisks.Write a method named printTriangle that receives a non-negative integer n and prints a triangle of asterisks as follows: first a line of n asterisks, followed by a line of n-1 asterisks, and then a line of n-2 asterisks, and so on.For example, if the method received 5 it would print:* * * * ** * * ** * ** **The method must not use a loop of any kind (for, while, do-while) to accomplish its job. The method should invoke printStars to accomplish the task of printing a single line.

public static void clear(int[] a, int n) { if (n > 0) { a[n - 1] = 0; clear(a, n - 1); } }

The elements of an int array can be set to 0 (i.e., the array can be cleared) recursively as follows: An array of size 0 is already cleared; Otherwise, set the last of the uncleared elements of the array to 0, and clear the rest of the array Write a void method named clear that accepts an int array, and the number of elements in the array and sets the elements of the array to 0.

public static void clear(int[] a, int n) { if (n > 0) { a[n - 1] = 0; clear(a, n - 1); } }

Write the definition of a method named copy that receives a reference to a Scanner object associated with a stream of input. The method reads all the strings remaining to be read from the stream and displays them, one on a line with no other spacing, onto standard output.The method must not use a loop of any kind (for, while, do-while) to accomplish its job.

public static void copy(Scanner in) { if (!in.hasNext()) return; else { System.out.println(in.next()); copy(in); } }


Related study sets

Urinalysis Ch 5 Practice Questions

View Set

31 Pairs of Spinal Nerves & 12 Pairs of Cranial Nerves

View Set

Ch. 22 & 23- Common Child and Adolescent Mental Health Disorders

View Set