1

I've got a set of recursion problems that I need to do. I've completed 3 out of the 4 of them we were given, but I'm having a hard time wrapping my head around this last one. I don't necessarily want the actual answer, but maybe just point me in the right direction, because I'm not even seeing what my stop condition should be on this one. And note, it has to be recursive, no loops, etc.

Thanks in advance for any help provided!

Write recursive method arrayRange that returns the maximum integer minus the minimum integer in the filled array of ints. Use recursion; do not use a loop. The following assertions must pass (note the shortcut way to pass a reference to a new array--it saves your writing a bit of code (this passes an array built as a parameter):

assertEquals(2, rf.arrayRange(new int[] { 1, 2, 3 } ));

assertEquals(2, rf.arrayRange(new int[] { 3, 2, 1 } ));

assertEquals(0, rf.arrayRange(new int[] { 3 } ));

assertEquals(3, rf.arrayRange(new int[] { -3, -2, -5, -4 } ));

// Precondition: a.length > 0 public int arrayRange(int[] a)

3
  • asking for homework help, is not a good thing here. Commented Mar 26, 2011 at 6:40
  • 3
    Asking for help is fine. Asking us to do it is not. Commented Mar 26, 2011 at 6:42
  • True! And the OP does not want a straight up answer but help. Commented Mar 26, 2011 at 6:43

1 Answer 1

2

The stop condition is when there are only two items left: the maximum and minimum. Then just return the difference. (Also handle the case of 1 or 0 items, consider input such as in the test cases.)

Now .. how to reduce the list each pass? :) I would consider inspecting the first three values at a time (of the three, only two should remain in the recursive step).

Happy homeworking.

Sign up to request clarification or add additional context in comments.

3 Comments

That makes total sense now that you put it like that. Thanks a bunch! Gonna get to working on that solution. Should I post the solution when I get it or is that a bad idea?
@user677786 If you do wish to post a solution here, consider updating your original post (with a disclaimer/warning that your solution is below: it might take away the fun for someone else though!). I'd at least wait until after the assignment is due ;-)
Ok, got it figured out :P I'll post the solution after the due date :P Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.