Jump to content

Need help understanding this program

- - - - -

  • Please log in to reply
2 replies to this topic

#1
bloodchains

bloodchains

    Learning Programmer

  • Members
  • PipPipPip
  • 73 posts
In the CodingBat website, I'm doing this array problem:

CodingBat Java Array-2 centeredAverage

I found the answer on the internet, which is:
public int centeredAverage(int[] nums) {
   int largest = 0, smallest = 0, result = 0;
      for(int i = 0; i < nums.length; i++) {
         if(nums[i] >= nums[largest] && i != smallest) {
            largest = i;
         } else if(nums[i] <= nums[smallest] && i != largest) {
            smallest = i;
         }
      }

      for(int i = 0; i < nums.length; i++) {
         if(i != largest && i != smallest) {
            result += nums[i];
         }
      }

      return (int)(result / (nums.length - 2)); }
But I'm having a hard time understanding what's going on here. First, I don't get why i is being used in the first for-loop to declare largest and smallest. Isn't it supposed to be "nums" for the first loop? Also, why does i need to be compared to smallest and largest to see if they're not equal to [I]i?

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
You're keeping track of WHERE the smallest and largest values are, not what they are.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
bloodchains

bloodchains

    Learning Programmer

  • Members
  • PipPipPip
  • 73 posts
Ooooh, I get it now. I was too focused on how to get the value of the largest and smallest and didn't see that you can just get their position in the array. Thanks!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users