1

JAVA Recursion: For this assignment, you will be working with various methods to manipulate strings using...

Question

JAVA Recursion: For this assignment, you will be working with various methods to manipulate strings using...

JAVA Recursion: For this assignment, you will be working with various methods to manipulate strings using recursion. The method signatures are included in the starter code below, with a more detailed explanation of what function the method should perform. You will be writing the following methods:

  • stringClean()
  • palindromeChecker()
  • reverseString()
  • totalWord()
  • permutation()

You will be using tools in the String class like .substring(), .charAt(), and .length() in all of these methods, so be careful with indices. If you get stuck, think about the base case of the method, then what needs to be done in the recursive case.

Do not use a loop in any of the methods except permutationHelper(). You may use a loop in permutationHelper() but there should be a recursive call in the method.

Include your own testing in main after instantiating an object of the class to check that your methods are working as expected.

For more recursion practice (or any other subject practice with Java), visit Coding Bat for some great problems to test your skills.

public class Main {


public static void main(String[] args) {

}


/* stringClean()
* Given a string, return recursively a "cleaned" string
* where adjacent chars that are the same have been reduced
* to a single char. So "yyzzza" yields "yza".
*/
public String stringClean(String str){
}


/* palindromeChecker()
* Given a string, check if it is a palindrome recursively.
* Return true if the given word is a palindrome, and false if it is not.
* For example, "abcba" would yield true, but "abc" would not.
* A word is a palindrome if the letters in the word are symmetric.
*/
public boolean palindromeChecker(String word){
  
}


/* reverseString()
* Given a string, recursively reverse the letters to yield a new string.
* For example, if given "abcde", the method would yield "edcba".
*/
public String reverseString(String word){
  
}

/* totalWord()
* Given a string, recursively find the sum of the integer values of the characters in the word.
* Since characters have corresponding integer values from the ASCII table, you are able to sum them into a single integer.
* For example, if given "abc", the method would return 294.
*/
public int totalWord(String word){

}

/*
* The following method is given to you, and you will be responsible for completing the permutationHelper method it calls.
* Sometimes, helper methods are used for recursive methods when another parameter is needed to recursively call a method repeatedly, but passing that parameter initially doesn't make sense.
*/
public String permutation(String word){
return permutationHelper(" ", word);
}

/* permutationHelper()
* This method is called by the permutation method.
* Given a string, return a string that lists all possible permutations of the letters in the string, with spaces preceding each permutation.
* For example, "123" would give " 123 132 213 231 312 321".
* The perm parameter keeps track of the current permutation you are creating.
* Consider using the a for loop to call the method recursively a certain number of times with different parameters, so you cover all permutations.
*/
public String permutationHelper(String perm, String word) {
}
  

}

Answers

Here are the required methods with the driver main(). I have kept some inline comments to help explain the logic. Still, if there is something that is not very clear, do let me know and I will be glad to assist you back.

package myStore;

public class StringCode {

   /* stringClean()
   * Given a string, return recursively a "cleaned" string
   * where adjacent chars that are the same have been reduced
   * to a single char. So "yyzzza" yields "yza".
   */
   public static String stringClean(String str){      
       // base case, where the string is made of only 1 character
       if (str.length()==1)
           return str;
       // In any other case, we need to see if the first character is equal to
       // the next character or not, in the later case, we need to recurse the
       // method with the new substring of the original word. In the former case,
       // we should just ignore the character and move on with adding it only once
       // in the final string.
        if (str.charAt(0) != str.charAt(1))
            return str.charAt(0) + stringClean(str.substring(1));      
        return stringClean(str.substring(1));
   }


   /* palindromeChecker()
   * Given a string, check if it is a palindrome recursively.
   * Return true if the given word is a palindrome, and false if it is not.
   * For example, "abcba" would yield true, but "abc" would not.
   * A word is a palindrome if the letters in the word are symmetric.
   */
   public static boolean palindromeChecker(String word){
       // Base case: string is of length 0 or 1, it's a palindrome, so return true.
        if(word.length() == 0 || word.length() == 1)
            return true;       
        /*
         * Start with the first and last characters of the string.
         * If they match, keep on checking the same by matching the next character
         * with the second last character until the middle of the string is found.
         * Any failure found will make the string non-palindrome.
         */
        if(word.charAt(0) == word.charAt(word.length()-1))
           // .substring() will keep on making the small substrings out of the original string
           return palindromeChecker(word.substring(1, word.length()-1));
        return false;
   }


   /* reverseString()
   * Given a string, recursively reverse the letters to yield a new string.
   * For example, if given "abcde", the method would yield "edcba".
   */
   public static String reverseString(String word){
       /*
       * Return the entire word if it's empty as there is no need to reverse.
       */
       if (word.length() == 0)
             return word;
       // Start appending the first character of the string at the end of the new string
       // and recurse the new substring after cutting the first character out of it.
       return reverseString(word.substring(1)) + word.charAt(0);
   }

   /* totalWord()
   * Given a string, recursively find the sum of the integer values of the characters in the word.
   * Since characters have corresponding integer values from the ASCII table, you are able to sum
   * them into a single integer.
   * For example, if given "abc", the method would return 294.
   */
   public static int totalWord(String word){
       /*
       * Base case: when the string is of 1 character only, just return the ASCII value
       * of that character
       */
       if (word.length() == 1)
           return (int)word.charAt(0);
       /*
       * Else, we need to keep adding the ASCII value of first character with the
       * recursed value of the substring found by cutting the first character of the
       * original string.
       */
       return (int)word.charAt(0) + totalWord(word.substring(1, word.length()));
   }

   /*
   * The following method is given to you, and you will be responsible for completing the
   * permutationHelper method it calls. Sometimes, helper methods are used for recursive methods
   * when another parameter is needed to recursively call a method repeatedly, but passing that
   * parameter initially doesn't make sense.
   */
   public static String permutation(String word){
       return permutationHelper(" ", word);
   }

   /* permutationHelper()
   * This method is called by the permutation method.
   * Given a string, return a string that lists all possible permutations of the letters in the
   * string, with spaces preceding each permutation.
   * For example, "123" would give " 123 132 213 231 312 321".
   * The perm parameter keeps track of the current permutation you are creating.
   * Consider using the a for loop to call the method recursively a certain number of times with
   * different parameters, so you cover all permutations.
   */
   public static String permutationHelper(String perm, String word) {
       /*
       * Base case: If the word is empty, just print the delimiter along with the word.
       */
        if (word.length()==0) System.out.print(perm + word);
        /*
         * Otherwise, as instructed, using a for loop to keep getting the permutations.
         * For example, in first iteration, we get the .charAt(0) that is 1 (support the
         * string is "123") appended with "23" (found by word.substring(i+1, word.length()))
         * This goes on until we are left with only no characters in the string.
         */
        for (int i = 0; i < word.length(); i++) {
              permutationHelper(perm + word.charAt(i), word.substring(0,i) + word.substring(i+1, word.length()));
        }
       return "";
   }
  
   // Driver code main()
   public static void main(String[] args) {
       System.out.println(stringClean("aabbbbbbccdbbxrr"));
       System.out.println(palindromeChecker("abcdcbaa"));
       System.out.println(reverseString("reverse me"));
       System.out.println(totalWord("abc"));
       System.out.println(permutation("123"));
   }
}

IDE and Execution screenshot :

StringCode StringCode.java X myStore ▸ src myStore ▸ 1 package myStore; 3 public class StringCode { HNM to /* stringClean() *

StringCode.java X myStore ▸ s rc #myStore ▸ StringCode permutationHelper(String, String): String 61 } 62 630 /* totalWord) *


Similar Solved Questions

1 answers
Use python In class, we've studied Singly-Linked Lists which are made of nodes that point at...
use python In class, we've studied Singly-Linked Lists which are made of nodes that point at subsequent nodes. One of the biggest annoyances with Linked Lists is the difficulty of going backwards through a list (such as getting the previous node or traversing the list backwards). An intuitive so...
1 answers
Problem 11-13 Replacement Analysis The Everly Equipment Company's flange-lipping machine was purchased 5 years ago for...
Problem 11-13 Replacement Analysis The Everly Equipment Company's flange-lipping machine was purchased 5 years ago for $100,000. It had an expected life of 10 years when it was bought and its remaining depreciation is $10,000 per year for each year of its remaining life. As older flange-lippers ...
1 answers
An article contained the following observations on degree of polymerization for paper specimens for which viscosity...
An article contained the following observations on degree of polymerization for paper specimens for which viscosity times concentration fell in a certain middle range. 413 421 421 422 425 427 431 430 437 439 446 447 448 453 460 463 465 (a) Calculate a two-sided 95% confidence interval for true avera...
1 answers
According to each model, what will the light level be after 10 hours? Please EXPLAIN Graph...
According to each model, what will the light level be after 10 hours? Please EXPLAIN Graph 1: Quadratic Regression Graph 2: Exponential Regression Time (h) Light Level (lumens) 0.860 0 0.695 1 0.562 2 0.455 0.367 4 0.305 5 6 0.247 Light Level (Lumens) vs. Time (H) Light Level (Lumens) 0.855 0.167...
1 answers
Aqueous sulfuric acid H2SO4 reacts with solid sodium hydroxide NaOH to produce aqueous sodium sulfate Na2SO4...
Aqueous sulfuric acid H2SO4 reacts with solid sodium hydroxide NaOH to produce aqueous sodium sulfate Na2SO4 and liquid water H2O. If 70.8g of sodium sulfate is produced from the reaction of 87.29g of sulfuric acid and 111.1g of sodium hydroxide, calculate the percent yield of sodium sulfate. Be sur...
1 answers
Partly comp Click the icon to view the schedules) i les of cost of goods manufactured...
partly comp Click the icon to view the schedules) i les of cost of goods manufactured Compute the missing amounts. Snyder Corp. 10.400 Rustic Gear Fit Apparel 2500 3000 0 Data Table 14.500 10.700 20.000 35.900 20.200 10 BCO Snyder Corp Rustic Gear Apparel 002005 Beginning Wor c es wory Direct Materi...
1 answers
10. The moment generating function of the random variable X is given by My(t) = exp{2e*...
10. The moment generating function of the random variable X is given by My(t) = exp{2e* – 2} and that of Y by My(t) = fet +. Assuming that X and Y are independent, find (a) P{X + Y = 2). (b) P{XY = 0}. (c) E(XY)....
1 answers
Kayak Co. budgeted the following cash receipts (excluding cash receipts from loans received) and cash payments...
Kayak Co. budgeted the following cash receipts (excluding cash receipts from loans received) and cash payments (excluding cash payments for loan principal and interest payments) for the first three months of next year. Cash Receipts Cash payments January $ 517,000 $ 458,300 February 403,...
1 answers
SHOW WORK, FOR PRACTICE. 1B) EWEX has been working with utility companies to set up expensive...
SHOW WORK, FOR PRACTICE. 1B) EWEX has been working with utility companies to set up expensive power generating windmills. In order for a site to be effective, the average wind speed must be more than 20 mph. At a specific site, EWEX took a sample of forty-five wind speed readings. The sample avera...
1 answers
What are the differences between personality structures and mental mechanisms ?
what are the differences between personality structures and mental mechanisms ?...
1 answers
10 pts Question 3 a) Explain the reason why heat is released when a hydrocarbon fuel...
10 pts Question 3 a) Explain the reason why heat is released when a hydrocarbon fuel is burned in a combustion chamber. b) Why excess alr is necessary to use in an actual combustion? Explain. c) n - Dodecane (C12H%) in gas form is burned in a combustion chamber with 150% excess air. Determine the fo...
1 answers
Given is a CPM project network diagram as shown below. A F Start E H End...
Given is a CPM project network diagram as shown below. A F Start E H End B D G Start H Activity day А 6 B 3 с 8 D 7 E 4 F 9 G 4 End 0 0 6 a) The Project Completion time = days. b) The Earliest Start time, ES, of Activity G - days. c) The Latest Finish time, LF, of Acitivity - dayy d) The...
1 answers
Please show work(z critical value, error of margin calculation,p max and p min). 8. In a...
please show work(z critical value, error of margin calculation,p max and p min). 8. In a sample of 150 Americans, 30 said that they do not watch local TV channels, Use 95% confidence level to estimate the proportion of Americans who do not watch Local TV channels. Express your answer in Pain <p 2...
1 answers
The Ka of Tris is 8.5x10-9 and the pKa of Tris is 8.07. What are the...
The Ka of Tris is 8.5x10-9 and the pKa of Tris is 8.07. What are the [HA] and [A-] concentrations of this 0.50M buffer at pH 8.75? 3). I need to make a 0.50M Tris buffer with a pH of 8.75. I have access to Tris (a weak acid) and the sodium salt of Tris (think A). The Ka of Tris is 8.5x10-9 and the p...
1 answers
For each part, intersperse your equations with written explanation as to why your approach makes sense...
For each part, intersperse your equations with written explanation as to why your approach makes sense in terms of physical concepts. Treat each part as a “concept question”. 1) Two blocks of mass m hang from a wire as in Figure 22. The linear density of the wire is µ. Assume that ...
1 answers
The 400 V battery of a Tesla model S electric car stores 3.0 x 108J of...
The 400 V battery of a Tesla model S electric car stores 3.0 x 108J of energy. At 65 mph, the car can drive 250 mi before the battery is depleted. At this speed, what is the current delivered by the battery?...
1 answers
Question 2 Why use dc motors when ac power is delivered on the line? a. dc...
Question 2 Why use dc motors when ac power is delivered on the line? a. dc motors are grandfathered in from a time when dc power was delivered to the customer. b. dc mototrs maintain a higher efficiency while having a wide torque-speed charateristic. c. ac motors are more complicated and challenging...
1 answers
Is A system with an unper tubed Hamiltonian H Subjected to a perturbation HC Mon ,...
is A system with an unper tubed Hamiltonian H Subjected to a perturbation HC Mon , 3 . • Il (1 1 . i eil 2 0 ; H = da o vz; 0 0 -2 0 II 131 l-ai vei o 2, where a is a real Constant with The dimesions of an energy anda is a dimension less real Constant. as show that the following vectors are the...
1 answers
Need help with 3-6 Determination of Solubility Product Constant 10.7 Name Section PRE-LAB 1. In your...
Need help with 3-6 Determination of Solubility Product Constant 10.7 Name Section PRE-LAB 1. In your own words explain the common ion effect. The common ion effect is when the solubility of a salt is affected by the presence of an ion which is common to any of the ions in the salt. 2. What would ...

-- 0.010277--