bigDiff

From ggc

Jump to: navigation, search

In the javabat problem bigDiff, how do you find the Max. and Min. in the data set?

It says to use Math.min(v1, v2) or Math.max(v1, v2), but how would you determine the maximum or minimum between multiple?

This was my attempt:

public int bigDiff(int[] nums) 
{
int max;
int min;
if(nums.length >= 1)
 max = new Math.max(nums[0], nums[nums.length-1]);
 min = new Math.min(nums[0], nums[nums.length-1]);
 return max - min;
}

My next attempt:

public int bigDiff(int[] nums) 
{
  int minIndex = 0;
  int maxIndex = 20;  
  for (int i=1; i<values.length; i++) 
  {
    if (nums[i] < num[minIndex])
      minIndex = i;
    if (nums[i] > num[maxIndex])
      maxIndex = j;
  }
return j-i;
}

What is not right about these?

Answer

How do you know there are 20 elements in the array? There may only be 10 or 5, or 1 or 100. nums.length is the number of elements in the array and nums.lenght-1 is the last index into the array.

Your approach is good in that when you see something that exceeds the extreme, you reset the extreme's location. However, what you are attempting to return is the difference in the location of the extremes indexes (but you use the counter, not the indexes declared previously), not the difference in the extremes' elements. Remember, maxIndex is an index into the array and nums[maxIndex] is the element at position maxIndex. Be sure not confuse indexes with elements. See if these help solve your problems, which are quite commonly experienced by students learning to use arrays.





Views
Personal tools
Add to 
del.icio.usAdd to 
diggAdd to 
FacebookAdd to 
favoritesAdd to 
GoogleAdd to 
MySpaceAdd to 
PrintAdd to 
SlashdotAdd to 
StumbleUponAdd to 
Twitter