2

I have an array of double Double[] array = new Double[5];

For example, if the array contains data like this:

{0.5 , 1.5 , 1.1 , 0.6 , 2}

How do I find the number that is closest to 1? The output should be 1.1, because it's the one that is closest to 1 in this case.

puretppc
  • 3,232
  • 8
  • 38
  • 65
julianconcepcion
  • 187
  • 3
  • 18

3 Answers3

6
var result = source.OrderBy(x => Math.Abs(1 - x)).First();

Requires using System.Linq; at the top of a file. It's O(n log(n)) solution.

Update

If you're really afraid about performance and want O(n) solution, you can use MinBy() extension method from moreLINQ library.

Or you could use Aggregate() method:

var result = source.Aggregate(
                new { val = 0d, abs = double.MaxValue },
                (a, i) => Math.Abs(1 - i) > a.abs ? a : new { val = i, abs = Math.Abs(1 - i) },
                a => a.val);
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • 1
    But sorting seems overly expensive. – H H Feb 02 '14 at 22:40
  • 2
    @HenkHolterman It's *O(n*log(n))* solution. I know *O(n)* is possible, but I would not be afraid about that unless array has thousands elements. – MarcinJuraszek Feb 02 '14 at 22:41
  • Yes, I knew there was something like MinBy(). Can probably expand on that to get the index if needed. – H H Feb 02 '14 at 22:53
3

You can achieve this in a simple way using LINQ:

var closestTo1 = array.OrderBy(x => Math.Abs(x - 1)).First();
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
3

Something like this should be easy to understand by any programmer and has O(n) complexity (non-LINQ):

double minValue = array[0];
double minDifference = Math.Abs(array[0] - 1);

foreach (double val in array)
{
    int dif = Math.Abs(x - 1);   

    if (dif < minValue) 
    {
        minDifference = dif;
        minValue = val;
    }
}

After this code executes, minValue will have your required value.

Code summary:

It will set the minimum value as the first element of the array. Then the difference will be the absolute value of the first element minus 1.

This loop will linear search the array and find the minimum value of the array. If the difference is less than the minimum value it will set a new minimum difference and minimum value.

puretppc
  • 3,232
  • 8
  • 38
  • 65
Vlad Schnakovszki
  • 8,434
  • 6
  • 80
  • 114
  • 2
    Yes, but very old-school. Good when performance is most important. – H H Feb 02 '14 at 22:55
  • My guess is that LINQ has better performance. Generally I prefer most non-LINQ solutions because it's easier to understand for beginners and I only learned about LINQ based on my previous questions. – puretppc Feb 02 '14 at 23:00