Chamkey
Chamkey

Reputation: 105

C# Find all values in an array closest to a given number

given:

int[] myArray = new int[]{-8, -17, 12, 8, 16, -3, 7, 3};

Find all values in array closest to 0.

Currently using another code found on the site but it only tells me 1 value.

int nearest = myArray.Select(p => new {Value = p, Difference = Math.Abs(p - searchValue)}).OrderBy(p => p.Difference).First().Value;

In the current case both -3 and 3 are closest to 0 but since -3 comes first it only outputs -3.

Is there another way to do this where it finds all values instead of just First()?

Upvotes: 0

Views: 1558

Answers (2)

Swetha
Swetha

Reputation: 467

Just to add to this. If you want to do this using O(n) complexity without sorting then you can do it this way :

 public List<int> GetClosestNumbers(int searchVal)
        {
            int[] myArray = new int[] { -8, -17, 12, 8, 16, -3, 7, 3 };
            int minimumDist = int.MaxValue;
            List<int> output = new List<int>();
            for (int i = 0; i < myArray.Length; i++)
            {
                var currentDistance = Math.Abs(myArray[i] - searchVal);
                if (currentDistance < minimumDist)
                {
                    minimumDist = currentDistance;
                    output.Clear();
                    output.Add(myArray[i]);
                }
                else if (minimumDist == currentDistance)
                {
                    output.Add(myArray[i]);
                }
            }

            return output;
        }

Upvotes: 3

djv
djv

Reputation: 15774

Use a grouping on the lowest absolute value

int[] result = myArray
    .OrderBy(i => Math.Abs(i - searchValue))
    .GroupBy(i => Math.Abs(i - searchValue))
    .First()
    .ToArray();

Upvotes: 2

Related Questions