New Semester
Started
Get
50% OFF
Study Help!
--h --m --s
Claim Now
Question Answers
Textbooks
Find textbooks, questions and answers
Oops, something went wrong!
Change your search query and then try again
S
Books
FREE
Study Help
Expert Questions
Accounting
General Management
Mathematics
Finance
Organizational Behaviour
Law
Physics
Operating System
Management Leadership
Sociology
Programming
Marketing
Database
Computer Network
Economics
Textbooks Solutions
Accounting
Managerial Accounting
Management Leadership
Cost Accounting
Statistics
Business Law
Corporate Finance
Finance
Economics
Auditing
Tutors
Online Tutors
Find a Tutor
Hire a Tutor
Become a Tutor
AI Tutor
AI Study Planner
NEW
Sell Books
Search
Search
Sign In
Register
study help
computer science
building java programs a back to basics approach
Building Java Programs A Back To Basics Approach 5th Edition Stuart Reges, Marty Stepp - Solutions
Write a method called pairCounts that accepts a list of strings representing individual words and counts the number of occurrences of all 2-character sequences of letters in those words. For example, suppose the list contains ["banana", "bends", "i", "mend", "sandy"]. This list contains the
Write the map returned when the following method is passed the following maps:a. map1: {bar=1, baz=2, foo=3, mumble=4}, map2: {1=earth, 2=wind, 3=air, 4=fire}b. map1: {five=105, four=104, one=101, six=106, three=103, two=102}, map2: {99=uno, 101=dos, 103=tres, 105=quatro}c. map1: {a=42, b=9, c=7,
What is recursion? How does a recursive method differ from a standard iterative method?
Write a recursive method called starString that accepts an integer as a parameter and prints to the console a string of stars (asterisks) that is 2n (i.e., 2 to the nth power) long. For example,starString(0) should print * (because 20 == 1)starString(1) should print ** (because 21 ==
Write a recursive program to solve the “Missionaries and Cannibals” problem. Three missionaries and three cannibals come to a river and find a boat that holds two. If the cannibals ever outnumber the missionaries on either bank, the missionaries will be eaten. How might they cross safely?Your
Consider the following method:For each of the following calls, indicate the output that is produced by the method:a. mystery1(1);b. mystery1(2);c. mystery1(3);d. mystery1(4);e. mystery1(16);f. mystery1(30);g. mystery1(100); public static void mystery1 (int n) { if (n
Write a method called writeSequence that accepts an integer n as a parameter and prints to the console a symmetric sequence of n numbers composed of descending integers that ends in 1, followed by a sequence of ascending integers that begins with 1. The following table indicates the output that
Write a recursive program to solve the Towers of Hanoi puzzle. The puzzle involves manipulating disks that you can move between three different towers. You are given a certain number of disks (four in this example) stacked on one of the three towers. The disks have decreasing diameters, with the
The Koch snowflake is a fractal that is created by starting with a line segment, then recursively altering it as follows:1. Divide the line segment into three segments of equal length.2. Draw an equilateral triangle that has the middle segment from step 1 as its base.3. Remove the line segment that
Consider the following method:For each of the following calls, indicate the output that is produced by the method:a. mystery2(113);b. mystery2(70);c. mystery2(42);d. mystery2(30);e. mystery2(10); public static void mystery2 (int n) { if (n > 100) { System.out.print (n); } else { mystery2 (2 * n);
Write a recursive method called doubleDigits that accepts an integer n as a parameter and returns the integer obtained by replacing every digit of with two of that digit. For example, doubleDigits(348) should return 334488. The call doubleDigits(0) should return 0. Calling doubleDigits on a
Write a program that uses recursive backtracking to generate all anagrams from a phrase typed by the user. An anagram is a word or phrase made by rearranging the letters of another word or phrase. For example, the words “midterm” and “trimmed” are anagrams. If you ignore spaces and
Consider the following method:For each of the following calls, indicate the output that is produced by the method:a. mystery3(0);b. mystery3(1);c. mystery3(2);d. mystery3(4);e. mystery3(5); public static void mystery3 (int n) { if (n
Write a recursive method called writeBinary that accepts an integer as a parameter and writes its binary representation to the console. For example, writeBinary(44) should print 101100.
Write a program that uses recursive backtracking to play the game of Boggle. Boggle is a word game played on a 4 x 4 grid where the player tries to find all valid dictionary words that can be made by tracing a path between adjacent letters from the board. Each link in the path can be horizontal,
Consider the following method:For each of the following calls, indicate the output that is produced by the method:a. mysteryXY(4, 1);b. mysteryXY(4, 2);c. mysteryXY(8, 2);d. mysteryXY(4, 3);e. mysteryXY(3, 4); public void mysteryXY (int x, int y) { if (y == 1) { System.out.print (x); } else {
Write a recursive method called writeSquares that accepts an integer parameter and prints the first squares separated by commas, with the odd squares in descending order followed by the even squares in ascending order. For example, writeSquares(8); prints the following output:49, 25, 9, 1, 4, 16,
Write a program that uses recursive backtracking to find all ancestors and descendants of a person given a file of familial relationships. For ancestors it must show all parents, all grandparents, all great grandparents, etc. For descendants it must show all children, all grandchildren, all great
Convert the following iterative method into a recursive method: // Prints each character of the string reversed twice. // doubleReverse ("hello") prints oolllleehh public static void doubleReverse (String s) { for (int i = s.length () 1; i >= 0; i--) { System.out.print (s.charAt (i));
Write a recursive method called writeChars that accepts an integer parameter and that prints out a total of characters. The middle character of the output should always be an asterisk ( "*" ). If you are asked to write out an even number of characters, then there will be two asterisks in the middle
What is a call stack, and how does it relate to recursion?
Write a recursive method called multiplyEvens that returns the product of the first even integers. For example, multiplyEvens(1) returns 2 and multiplyEvens(4) returns 384 (because 2 * 4 * 6 * 8 = 384). The method should throw an IllegalArgumentException if it is passed a value less than or equal
What would be the effect if the code for the reverse method were changed to the following? public static void reverse (Scanner input) { if (input.hasNextLine () ) { // recursive case (nonempty file) String line = input.nextLine (); System.out.println (line) ; // swapped order reverse (input); //
Write a recursive method called sumTo that accepts an integer parameter and returns a real number representing the sum of the first reciprocals. In other words, sumTo(n) returns (1 + 1/2 + 1/3 + 1/4+. . .+1/n). For example, sumTo(2) should return 1.5. The method should return 0.0 if it is passed
What would be the effect if the code for the reverse method were changed to the following? public static void reverse (Scanner input) { if (input.hasNextLine () ) { // recursive case (nonempty file) reverse (input); // moved this line String line = input.nextLine () ; System.out.println (line);
Write a recursive method called digitMatch that accepts two nonnegative integers as parameters and that returns the number of digits that match between them. Two digits match if they are equal and have the same position relative to the end of the number (i.e., starting with the ones digit). In
The following method is an attempt to write a recursive pow method to compute exponents. What is wrong with the code? How can it be fixed? public static int pow (int x, int y) { pow (x, y - 1); return x
Write a recursive method called repeat that accepts a string and an integer as parameters and that returns concatenated together times. For example, repeat("hello", 3) returns "hellohellohello", and repeat( "ok", 1) returns "ok", and repeat( "bye", 0) returns "". String concatenation is an
What are the differences between the two versions of the pow method shown in Section 12.3? What advantage does the second version have over the first version? Are both versions recursive?
Write a recursive method called isReverse that accepts two strings as parameters and returns true if the two strings contain the same sequence of characters as each other but in the opposite order (ignoring capitalization), and false otherwise. For example, the call of isReverse( "hello ", "eLLoH
Consider the following method:For each of the following calls, indicate the value that is returned:a. mystery4(6, 13)b. mystery4(14, 10)c. mystery4(37, 10)d. mystery4(8, 2)e. mystery4(50, 7) public static int mystery4 (int x, int y) { if (x < y) { return x; } else { return mystery4 (x - y, y):
Write a recursive method called indexOf that accepts two strings as parameters and that returns the starting index of the first occurrence of the second string inside the first string (or -1 if not found). For example, the call of indexOf( "Barack Obama ", "bam ") would return 8. (Strings already
Consider the following method:For each of the following calls, indicate the value that is returned:a. mystery5(5, 7)b. mystery5(12, 9)c. mystery5(-7, 4)d. mystery5( – 23, –48)e. mystery5(128, 343) public static int mystery5 (int x, int y) { if (x < 0) { return -mystery5 (-x, y); } else if (y <
Consider the following method:For each of the following calls, indicate the value that is returned:a. mystery6(7, 1)b. mystery6(4, 2)c. mystery6(4, 3)d. mystery6(5, 3)e. mystery6(5, 4) public static int mystery6 (int n, int k) { if (k == 0 || k == n) { return 1; } else if (k > n) { return 0; } else
Write a recursive method vowelsToEnd that takes a string as a parameter and returns a string in which all of the vowels have been moved to the end. The vowels should appear in reverse order of what they were in the original word. For example, the call of vowelsToEnd("beautifully") should return
Convert the following iterative method into a recursive method: // Returns n!, such as 5! = 1*2*3*4 *5 %3D public static int factorial (int n) { int product 1; for (int i = 1; i
Write a recursive method called evenDigits that accepts an integer parameter and that returns the integer formed by removing the odd digits from it. For example, evenDigits(8342116) returns 8426 and evenDigits (-34512) returns -42. If the number is 0 or has no even digits, such as 35159 or 7,
The following method has a bug that leads to infinite recursion. What correction fixes the code? // Adds the digits of the given number. // Example: digitsum (3456) returns 3+4+5+6 = 18 public static int digitSum (int n) { if (n > 10) { // base case (small number) return n; } else { // recursive
Write a recursive method called permut that accepts two integers n and as parameters and returns the number of unique permutations of r items from a group of n items. For given values of n and r, this value P(n, r) can be computed as follows:For example, permut(7, 4) should return 840 . It may be
Sometimes the parameters that a client would like to pass to a method don’t match the parameters that are best for writing a recursive solution to the problem. What should a programmer do to resolve this issue?
The Sierpinski carpet is a fractal that is defined as follows: The construction of the Sierpinski carpet begins with a square. The square is cut into nine congruent subsquares in a 3-by-3 grid, with the central subsquare removed. The same process is then applied recursively to the eight other
The Fibonacci sequence is a sequence of numbers in which the first two numbers are 1 and each subsequent number is the sum of the previous two Fibonacci numbers. The sequence is 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on. The following is a correct, but inefficient, method to compute the nth Fibonacci
The Cantor set is a fractal that is defined by repeatedly removing the middle thirds of line segments as shown in Figure 12.15.Write a program to draw the Cantor set on a DrawingPanel recursively.
What is a fractal image? How does recursive programming help to draw fractals?
Write a recursive method called waysToClimb that takes a positive integer value representing a number of stairs and prints each unique way to climb a staircase of that height, taking strides of one or two stairs at a time. Do not use any loops. Output each way to climb the stairs on its own line,
Write Java code to create and draw a regular hexagon (a type of polygon).
Write a recursive method called countBinary that accepts an integer n as a parameter and that prints all binary numbers that have exactly n digits in ascending order, each on its own line. All digits should be shown for all numbers, including leading zeros if necessary. Assume that n is
Why is recursion an effective way to implement a backtracking algorithm?
Write a recursive method called subsets to find every possible sub-list of a given list. A sub-list of a list L contains 0 or more of L’s contains 0 or more of ’s elements. Your method should accept a list of strings as its parameter and print every sub-list that could be created from elements
What is a decision tree? How are decision trees important for backtracking?
Write a recursive method called maxSum that accepts a list of integers, L and an integer limit as parameters and uses backtracking to find the maximum sum that can be generated by adding elements of L hat do not exceed n. For example, if you are given the list [7, 30, 8, 22, 6, 1, 14] and the limit
Draw the decision tree that would have resulted for Figure 12.9 if the backtracking solution had explored NE first instead of last in the recursive explore method. start (0,0) NE (0,1) (1,0) (1,1) NE N NE EN EE E NE NE N NE E NE NE (0,2) (1,1) (1,2) (1,1) (2,0) (2,1) /(1,2) (2,1) (2,2) NNNNNE NN NE
Write a recursive method called printSquares to find all ways to express an integer as a sum of squares of unique positive integers. For example, the call printSquares(200); should produce the following output:Some numbers (such as 128 or 0) cannot be represented as a sum of squares, in which case
The original North/East backtracking solution printed the following ways of traveling to (1, 2) in this order. In what order would they be printed if the solution had explored NE first instead of last?moves: N N Emoves: N E Nmoves: N NEmoves: E N Nmoves: NE N
Figure 12.12 shows only part of the decision tree for the first two levels. How many entries are there at the second level of the full tree? How many are at level 3 of the full tree? empty col l row 2 col I col | col l col l col l col l col I row | row 3 row 4 row 5 row 6 row 7 row 8 col 2 col 2
If our 8 Queens algorithm tried every possible square on the board for placing each queen, how many entries are there at the 8th and final level of the full tree? What does our algorithm do to avoid having to explore so many possibilities?
The 8 Queens explore method stops once it finds one solution to the problem. What part of the code causes the algorithm to stop once it finds a solution? How could the code be modified so that it would find and output every solution to the problem?
The following code is not robust against invalid user input. Describe how to change the code so that it will not proceed until the user has entered a valid age and grade point average (GPA). Assume that any int is a legal age and that any double is a legal GPA.Scanner console = new
Write classes to model a shopping list. Make an Item class that represents a grocery item’s name and price, such as tissues for $3. Also implement an ItemOrder class that represents a shopper’s desire to purchase a given item in a given quantity, such as five boxes of tissues. You might wish to
Write a program to reverse the lines of a file and also to reverse the order of the words in each line of the file. Use ArrayList s to help you.
Write a family database program. Create a class to represent a person and to store references to the person’s mother, father, and any children the person has. Read a file of names to initialize the name and parent–child relationships of each Person . (You might wish to create a file
Write a class that models a list of possibly overlapping rectangular twodimensional window regions, like the windows for the programs open on your computer. The order of the rectangles in the list implies the order in which they would display on the screen (sometimes called the “-order”), from
Extend the ranked choice voting case study to allow for incomplete preferences. Voters are normally allowed to fill out the ballot in an incomplete manner. For example, with the sample ballots with four candidates, you might have ballots that specify only a first choice or only two choices. When
Write a method called interleave that accepts two ArrayLists of integers a1 and a2 as parameters and inserts the elements of a2 into a1 at alternating indexes. If the lists are of unequal length, the remaining elements of the longer list are left at the end of a1. For example, if a1 stores [10, 20,
Write a method called mirror that accepts an ArrayList of strings as a parameter and produces a mirrored copy of the list as output, with the original values followed by those same values in the opposite order. For example, if an ArrayList variable called list contains the values ["a", "b", "c"],
Modify the Point class from Chapter 8 so that it defines a natural ordering by implementing the Comparable interface. Compare the Points by -major order; that is, points with smaller -coordinate values should come before those with higher -coordinate values. Break ties by comparing -coordinate
What is a natural ordering? How do you define a natural ordering for a class you’ve written?
Modify the TimeSpan class from Chapter 8 to include a compareTo method that compares time spans by their length. A time span that represents a shorter amount of time is considered to be “less than” one that represents a longer amount of time. For example, a span of 3 hours and 15 minutes is
Consider the following variable declarations:Integer n1 = 15;Integer n2 = 7;Integer n3 = 15;String s1 = "computer";String s2 = "soda";String s3 = "pencil";Indicate whether the result of each of the following comparisons is positive, negative, or 0:a. n1.compareTo(n2)b. n3.compareTo(n1)c.
Modify the CalendarDate class from this chapter to include a year field, and modify its compareTo method to take years into account when making comparisons. Years take precedence over months, which take precedence over days. For example, July 18, 1995, comes beforeMarch 2, 2001.
Use the compareTo method to write code that reads two names from the console and prints the one that comes first in alphabetical order. For example, the program’s output might look like the following:Type a name: Tyler DurdenType a name: Marla SingerMarla Singer goes before Tyler Durden
Write code to read a line of input from the user and print the words of that line in sorted order, without removing duplicates. For example, the program output might look like the following: Type a message to sort: to be or not to be that is the question Your message sorted: be be is not or
Describe how to arrange an ArrayList into sorted order. What must be true about the type of elements in the list in order to sort it?
Write the output produced when the following method is passed each of the following lists:a. [10, 20, 30]b. [8, 2, 9, 7, 4]c. [-1, 3, 28, 17, 9, 33] public static void mystery4 (ArrayList list) { for (int i = 0; i < list.size (); i++) { int element list.get (i); %3D list.remove (i); list.add (0,
Write the output produced when the following method is passed each of the following lists:a. [72, 20]b. [1, 2, 3, 4, 5, 6]c. [10, 20, 30, 40] public static void mystery3 (ArrayList list) { for (int i = list.size () 2; i > 0; i--) { %3D int a = list.get (i); int b = list.get (i + 1); list.set (i, a
Write the output produced when the following method is passed each of the following lists:a. [10, 20, 30]b. [8, 2, 9, 7, 4]c. [-1, 3, 28, 17, 9, 33] public static void mystery2 (ArrayList list) { for (int i = list.size () 1; i >= 0; i--) { if (i % 2 0) { %3D%3D list.add (list.get (i)); } else {
Write a method called clump that accepts an ArrayList of strings as a parameter and replaces each pair of strings with a single string that consists of the two original strings in parentheses separated by a space. If the list is of odd length, the final element is unchanged. For example, suppose
Write the output produced when the following method is passed each of the following lists:a. [2, 6, 1, 8]b. [30, 20, 10, 60, 50, 40]c. [-4, 16, 9, 1, 64, 25, 36, 4, 49] public static void mystery1 (ArrayList list) { for (int i = list.size () - 1; i > 0; i--) { if (list.get (i) < list. get (i - 1))
Write a method called filterRange that accepts an ArrayList of integers and two integer values min and max as parameters and removes all elements whose values are in the range min through max (inclusive). For example, if a variable called list stores the values [4, 7, 9, 2, 7, 7, 5, 3, 5, 1, 7, 8,
What is a wrapper class? Describe the difference between an int and an Integer .
Write a method called removeShorterStrings that accepts an ArrayList of strings as a parameter and removes from each pair of values the shorter string in the pair. If the list is of odd length, the final element is unchanged. For example, suppose that a list contains ["four", "score", "and",
The code that follows does not compile. Why not? Explain how to fix it.ArrayList numbers = new ArrayList<>();numbers.add(7);numbers.add(19);System.out.println(numbers);
Write a method called reverse3 that accepts an ArrayList of integer values as a parameter and reverses each successive sequence of three values in the list. If the list has extra values that are not part of a sequence of three, those values are unchanged. For example, if a list stores values [3, 8,
When the code that follows runs on an ArrayList of String s, it throws an exception. Why? for (String s: words) { System.out.println (s); if (s.equals ("hello")) { words.add ("goodbye"); }
Write a method called markLength4 that accepts an ArrayList of strings as a parameter and that places a string of four asterisks " **** " in front of every string of length 4. For example, suppose that a variable called list contains the values ["this", "is", "lots", "of", "fun", "for", "Java",
Given the ArrayList from problem 4, write a for-each loop that prints the uppercase version of each String in the list on its own line.Data from Problem 4Write code to insert two additional elements, " dark " and " and ", at the proper places in the list to produce the following ArrayList as the
Write a method called stutter that accepts an ArrayList of strings and an integer as parameters and that replaces every string with copies of that string. For example, if the list stores the values ["how", "are", "you?"] before the method is called and is 4, it should store the values ["how",
Given the ArrayList from problem 4, write code to print out the index at which your list contains the value "stormy" and the index at which it contains "dark". Do not use a loop.Data from Problem 4Write code to insert two additional elements, " dark " and " and ", at the proper places in the list
Write a method called removeInRange that accepts three parameters, an ArrayList of strings, a beginning string, and an ending string, and removes from the list any strings that fall alphabetically between the start and end strings. For example, if the method is passed a list containing the elements
Write code to print out whether or not a list of String s contains the value "IS". Do not use a loop.
Write code to declare an ArrayList holding the first 10 multiples of 2: 0, 2, 4,..., 18. Use a loop to fill the list with the proper elements.
Write code to remove from the list any Strings that contain the letter "a". The following should be the list’s contents after your code has executed:["It", "IS", "stormy", "night"]
Write code to change the second element’s value to "IS", producing the following ArrayList as the result:["It", "IS", "a", "dark", "and", "stormy", "night"]
Write code to insert two additional elements, " dark " and " and ", at the proper places in the list to produce the following ArrayList as the result:["It", "was", "a", "dark", "and", "stormy", "night"]
The next five questions refer to the following String elements:["It", "was", "a", "stormy", "night"]Write the code to declare an ArrayList containing these elements. What is the size of the list? What is its type?
Write a method called rangeBetweenZeroe s that takes as a parameter an ArrayList of integers and returns the number of indexes apart the two farthest occurrences of the number 0 are. For example, if the list stores the values [7, 2, 0, 0, 4, 0, 9, 0, 6, 4, 8] when the method is called, it should
Write a method called maxLength that takes an ArrayList of String s as a parameter and that returns the length of the longest String in the list. If your method is passed an empty ArrayList, it should return 0.
Write a method called removeZeroe s that takes as a parameter an ArrayList of integers and eliminates any occurrences of the number 0 from the list. For example, if the list stores the values [0, 7, 2, 0, 0, 4, 0] before the method is called, it should store the values [7, 2, 4] after the method
Write a method called removeDuplicates that takes as a parameter a sorted ArrayList of strings and eliminates any duplicates from the list. For example, if the list stores the values ["be", "be", "is", "not", "or", "question", "that", "the", "to", "to"] before the method is called, it should store
Write a method called minToFront that takes an ArrayList of integers as a parameter and moves the minimum value in the list to the front, otherwise preserving the order of the elements. For example, if a variable called list stores [3, 8, 92, 4, 2, 17, 9], the value 2 is the minimum, so your method
Showing 400 - 500
of 1041
1
2
3
4
5
6
7
8
9
10
11
Step by Step Answers