user677786
user677786

Reputation: 475

Java Homework Help - Recursion with array

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)

Upvotes: 1

Views: 1178

Answers (1)

user166390
user166390

Reputation:

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.

Upvotes: 2

Related Questions