2

I'm doing an assignment for a class, but I'm not sure why the code I wrote for these two methods do not work.

For the first method, I'm trying to compare the current position in the array with the next one and if the next one is larger, it becomes the largest. Other wise, the int at the current position becomes the largest. After going through the array with recursive method call, it will return the largest int in the array.

// This method takes an integer array as well as an integer (the starting index) and returns the largest number in the array.
public int largestRec(int[] arr, int pos)
{
    // TODO: implement this method
    int largest = arr[pos];
      if(pos == arr.length-1)
    {
        return largest;
    }
    else
    {
        if(arr[pos] < arr[pos+1])
        {
           largest = arr[pos+1];
        }
        else
        {
           largest = arr[pos];
        }
        pos++;
        largestRec(arr, pos);
    }
    return largest; // replace this statement with your own return
}

Second method. What I'm trying to do is have it pass a smaller version of the string through a recursive method call and then when the test class calls the method, it will print out the reverse of the string.

// This method reads a string and returns the string in the reversed order.
public String reverseStringRec(String s)
{
    // TODO: implement this method
    String reverse;
    int pos = 0;
    if(s=="" || s.length() <= 1)
    {
        return s;
    }
      else
    {
        reverse = reverseStringRec(s.substring(1)) + s.charAt(0);
    }
    return reverse; // replace this statement with your own return
}

I'm not sure how to write the code to make it do that(for the assignment, I can only modify the methods, not outside variables/methods/classes allowed), so I'd appreciate any advice/help you can offer. If you need more info, I'll be glad to provide it. Thanks.

Edit: My problem is that the first method does not return the largest. For my test array, it usually prints the first int, or the second one(if it is larger than the first, but does not check the rest). For the second one, my test class(made by my professor), gives the message 'String index out of range" and I don't know how to fix that. I looked at Jason's suggestion, and put the suggested solution in, but it doesn't seem to be working for my case.

Edit2: The new version of reverseStringRec() now works. Now I need to fix largestRec(). Question is still open if anyone can offer any help.

Edit3: Although I fixed reverseStringRec(), someone gave an answer containing a for loop. I failed to mention that I cannot use loops for this assignment, so I apologize for the inconvenience. I'll put the output of the current largestRec() below if you need to see what results it yields as it is now.

Test 3: largest(10) ==> [Passed] Expected: 10 Yours: 10

Test 4: largest(10, 20, 30, 40, 50, 60) ==> [Failed] Expected: 60 Yours: 20

Test 5: largest(70, 20, 30, 40, 50, 10) ==> [Passed] Expected: 70 Yours: 70

Test 6: largest(70, 20, 100, 40, 50, 10) ==> [Failed] Expected: 100 Yours: 70

Edit4: Solution found for both methods. For largestRec(), please look at the solutions offered below. For reverseStringRec(), you can use the one in this post or one of the suggested ones below.

william h
  • 47
  • 5
  • Your `largestRec()` method looks wrong, and you are not even using it. – Tim Biegeleisen Mar 04 '16 at 01:13
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your code **and** accurately describe the problem. In this posting (which should be two separate posts), you've failed to display the actual problem. "... do not work" is not a problem description. – Prune Mar 04 '16 at 01:13
  • @TimBiegeleisen I know it's wrong, that's why I'm asking. I'm not sure how to write the code for it. – william h Mar 04 '16 at 01:26
  • @Jason I took a look at your link and tried the suggested solution, but it's still not printing the reverse of the string. – william h Mar 04 '16 at 01:27
  • @Jason Ah. Sorry. Your suggested link does work. I just didn't include the str.length() <= 1 part. It only solves half my problem, though. – william h Mar 04 '16 at 01:48

3 Answers3

1

Right off the bat, there's a pretty glaring issue with the second method. In it, you recursively call upon the method reverseString, and the argument for that is a substring. However, in this substring, you are attempting to make the substring longer than the original parameter, s - In essence, by including s.length() + 1, the substring() method attempts to create a substring with the character at index s.length() + 1, which does not exist.

For actually reversing the String input to the method, I would highly recommend using the charAt() method.

Ricardo Iglesias
  • 595
  • 2
  • 6
  • 16
  • Yeah. I realized that and removed it. I'll edit my post with the version of reverseStringRec() that works. Now, I just need to fix largestRec(). – william h Mar 04 '16 at 01:36
0

For reversing a String with a recursive method you can do it this way: public

   static String reverseStr(String str) {
        if (str.length() == 1)
            return str;
        else
            return str.charAt(str.length()-1) + reverseStr(str.substring(0, str.length()-1));  
    }

    public static void main(String[] args) {
        System.out.println(reverseStr("String to be reversed"));
    }

Another simple way to reverse a String (not recursive):

   public static String reverseStringRec(String s) {
        String reverse = "";
        int pos = 0;
        for (int i = s.length()-1; i >= 0; i--) {
            reverse += s.charAt(i);
            pos++;
        }
        return reverse;
    }

    public static void main(String[] args) {
        System.out.println(reverseStringRec("String to be reversed"));
    }

For your first part of the question, here is the solution:

   static int findMax(int[] arr, int length) {
        if (length == 1) {
            return arr[0];
        }
        return max(findMax(arr, length - 1), arr[length - 1]);
    }

    private static int max(int num1, int num2) {
        return num1>num2 ? num1 : num2;
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 3, 55, 200, 33};
        System.out.println(findMax(arr, arr.length));
    }
goncalopinto
  • 433
  • 2
  • 8
  • 2
    I appreciate you taking the time to make the code, but for this assignment, I have to use a recursive method call without any loops. Sorry, I forgot to mention that in my post. – william h Mar 04 '16 at 01:39
  • No worries. I noticed that you got it sorted already. And there is already a proposed solution for your other question. Cheers – goncalopinto Mar 04 '16 at 01:57
  • I just edited my answer o meet what it's being asked in your question (String reverse). – goncalopinto Mar 04 '16 at 02:06
  • Thanks for editing. Zaid's solution is good, but for my assignment, I can't add additional parameters(his code has int index), so I'm still trying to find a solution that can get the largest int with just the array and position as parameters. – william h Mar 04 '16 at 02:13
  • I edited my post with the solution for your largest number. Check if it's ok or if you need some changes. – goncalopinto Mar 04 '16 at 02:23
  • Thank you very much for coming back to provide another solution. You and Zaid helped a lot. I'm not sure whose answer to accept since they're both very good. – william h Mar 04 '16 at 02:33
  • Lol. Feel free do you what your conscience tells you to do. At least an upvote. ;) – goncalopinto Mar 04 '16 at 02:34
  • It says I need 15 rep to change the vote. I only have 11. I did click upvote, so maybe it'll show up when my rep changes to 15 or more. Thanks again. – william h Mar 04 '16 at 02:40
  • That's fine. You're welcome. Cheers. – goncalopinto Mar 04 '16 at 02:42
0

Check out these methods that find largest number and reverse the strings. Your solutions were pretty close. This is how I would implement these. You needed in index to track the array largest number, otherwise what you can do is pass in the first number and assume its the largest, and every time you find the largest replace it, and once you reach the end of the array you return the largest.

public String reverseString( String str )
{
    if(str.length()==1){
        return str;
    }
    return str.charAt( str.length() - 1 ) + reverseString( str.substring( 0, str.length() - 1 ) );

}
// initialize pos to 0
public int getLargest( int[] arr, int pos )
{
    int largest = arr[pos];
    if ( pos + 1 >= arr.length ) {
        return largest;
    }

    int second = getLargest( arr, pos + 1 );
    return largest > second ? largest : second;
}
Zaid Qureshi
  • 1,203
  • 1
  • 10
  • 15
  • Thanks for the answer, but I can't use an index because I'm not allowed to modify the method's parameters for the assignment. I can only use (int[] arr, int pos). If you have a solution that can get the largest int from the array with just those two parameters, I would really appreciate it. – william h Mar 04 '16 at 02:01
  • Sorry didnt know it was a restriction, it is done. Had to give it a thought, 3 params was the first thing that came into my mind. – Zaid Qureshi Mar 04 '16 at 02:09
  • Thanks for the solution. I think my original code didn't work because I didn't have int second. Not sure, but your solution was quick and easy. – william h Mar 04 '16 at 02:41
  • The reason it didnt work was because you were not storing the largest value. My method compares the largest value (value stored at pos) with the largest value in the positions after `pos`. So it keeps breaking it down to the last two in the array. Last pos is simply returned, then it would compare last two with each other and return greatest, then second last and third last would be compared and largest value would be returned, etc all the way to the top – Zaid Qureshi Mar 04 '16 at 03:04