3
\$\begingroup\$

I'm looking for criticism on the following method used to determine if a collection ofIntegers forms an arithmetic sequence:

    public boolean isArithmetic(Integer[] nums){    Set<Integer> result = new HashSet<Integer>();    Collections.sort(Arrays.asList(nums));    for(int i = 0; i < nums.length -1; i++)    {        result.add(nums[i+1] - nums[i]);    }    if(result.size() > 1)        return false;    return true;}
Jamal's user avatar
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
askedFeb 24, 2016 at 16:46
KPZ's user avatar
\$\endgroup\$

1 Answer1

8
\$\begingroup\$

The basic method you're using seems to me rather roundabout. If you're going to write a loop to walk through the collection anyway, why not just check for the correct criteria there? e.g., something like this:

Integer diff = nums[1] - nums[0];for (int i=2; i<nums.length; i++)    if (nums[i] - nums[i-1] != diff)        return false;return true;

This can save quite a bit of work, and (especially if the numbers don't form an arithmetic sequence) may save a fair amount of storage as well. More importantly, it makes the intent immediately obvious, which (it seems to me) that inserting all the differences into a hash table doesn't.

One other specific detail of your code bothers me:

if(result.size() > 1)    return false;return true;

Anything of the formif (x) return true; else return false; can be expressed asreturn x;. In your case, the sense is reversed, so it can bereturn !x;, so you just wantreturn result.size() == 1; (but, as noted above, I'd rather eliminate this entirely).

If you really want to use the approach you've taken, I think it becomes a lot more reasonableif you take your loop and wrap it up into a generic algorithm. I'd probably call itadjacentDifference. Then you end up with something on this general order:

Set<Integer> result = new HashSet<Integer>(); Collections.sort(Arrays.asList(nums));Algorithms.adjacentDifference(nums, result);return result.size() == 1;

That's simple and neat enough that as long as you're sure this is outside the critical path (i.e., the extra time and space used don't matter) it would at least be worth considering.

answeredFeb 24, 2016 at 17:37
Jerry Coffin's user avatar
\$\endgroup\$
1
  • \$\begingroup\$Thanks, that makes sense. Most jobs I have had rarely seem to care as long as it works, it's good to get real useful feedback.\$\endgroup\$CommentedFeb 25, 2016 at 9:18

You mustlog in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.