Thread: Finding a number in array close to another number

1. Member
Join Date
Mar 2009
Posts
31
Rep Power
0

Finding a number in array close to another number

I am having trouble coming up with a method that will take an array of doubles and find the number in the array closest to the average of the array. I know how to make a for loop to find the average but I don't know how to implement a method that will find the double in the array closest to the average. How (in pseudo code) would I implement this?

2. Senior Member
Join Date
Nov 2009
Posts
235
Rep Power
8
You could have two variables: double distance, and int index = 0. then loop through your array and compute the distance away from the average: (distance = Math.abs(average - array[i]) then the next time check if the distance of that number is less than the stored distance. If it is less, then store it's distance to the var distance, and its index to var index. If it is greater, go to next number in the array( continue;)
Hope this helped.

3. Member
Join Date
Mar 2009
Posts
31
Rep Power
0
Yes thanks a lot! I really appreciate your time!