In: Computer Science
Exercise: Recursive List Processing
Part 1: Write a recursive method that returns the length (an int) of the longest String in a List of Strings. For each recursive call, remove the first String from the list and return the greater of the length of the String you removed or the result of calling the method on the remainder of the list. The base case should be that the size of the list is 0. Write a driver to verify that your code is correct.
Part 2: Write a recursive method that takes a list of Strings as its only parameter and returns a list of Integers, which are the lengths of the Strings in the List. This part of this exercise will be significantly similar to the lecture example in which a list of ints is consumed, producing a list of the squares of the ints. Each recursive call should send the list, but without the first String; as the recursion unwinds, create the list of Integers and add the length of the String your stripped out in the current call to the *beginning* of the list. Write a driver to verify that your code is correct. (language is java for this)
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! =========================================================================== public class Recursion { // PART 1 public static int longestLength(String[] s) { if (s.length == 0) return 0; else if (s.length == 1) return s[0].length(); else { String[] remaining = Arrays.copyOfRange(s, 1, s.length); int lengthRemaining = longestLength(remaining); if (lengthRemaining > s[0].length()) return lengthRemaining; else return s[0].length(); } } // PART 2 public static int[] lengthList(String[] s) { if (s.length == 0) return new int[]{0}; else if (s.length == 1) return new int[]{s[0].length()}; else { String[] remaining = Arrays.copyOfRange(s, 1, s.length); int[] lengths = lengthList(remaining); int[] newLengths = new int[1 + lengths.length]; newLengths[0] = s[0].length(); for (int i = 1; i <= lengths.length; i++) newLengths[i] = lengths[i - 1]; return newLengths; } } public static void main(String[] args) { String[] s = {"1", "123", "12345", "123456789", "1234567890"}; System.out.println(longestLength(s)); int lengths[] = lengthList(s); System.out.println(java.util.Arrays.toString(lengths)); } } =======================================================================