julianconcepcion
julianconcepcion

Reputation: 187

How to find data inside array that is most closest to a condition

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.

Upvotes: 2

Views: 419

Answers (3)

Vlad Schnakovszki
Vlad Schnakovszki

Reputation: 8601

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.

Upvotes: 3

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

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);

Upvotes: 6

BartoszKP
BartoszKP

Reputation: 35891

You can achieve this in a simple way using LINQ:

var closestTo1 = array.OrderBy(x => Math.Abs(x - 1)).First();

Upvotes: 3

Related Questions