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.

1
  • Do you want the number (1.1) or the position (2) ? Feb 2, 2014 at 22:41

3 Answers 3

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);
3
  • 1
    But sorting seems overly expensive. Feb 2, 2014 at 22:40
  • 2
    @HenkHolterman It's O(nlog(n))* solution. I know O(n) is possible, but I would not be afraid about that unless array has thousands elements. Feb 2, 2014 at 22:41
  • Yes, I knew there was something like MinBy(). Can probably expand on that to get the index if needed. Feb 2, 2014 at 22:53
3

You can achieve this in a simple way using LINQ:

var closestTo1 = array.OrderBy(x => Math.Abs(x - 1)).First();
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.

2
  • 2
    Yes, but very old-school. Good when performance is most important. Feb 2, 2014 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 2, 2014 at 23:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.