Werter
Werter

Reputation: 13

How can I find the closest number from an array, rounding down

What I'm looking to do is take an array of numbers which progressively get bigger determine the highest one I can round down to. I'm not sure if that makes sense, I will give an example. Keep in mind I am making the numbers more simple for the sake of explanation, removing the last digit wouldn't work. The array I am using has 100 numbers going into the millions.

int[] breakpoint = new int[] {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
     110, 120, 130, 140, 150, 160, 170, 180, 190, 200};
    int totalValue = 153;
    int valueDisplayed;
         //???
label.Text = valueDisplayed.toString();

So what I would want in this situation is to return a value of 15(the index of the item in the array), so I can then display that value (for example with a label). Surely there's got to be an easy way to do this? I could not find an answer anywhere.

Upvotes: 1

Views: 514

Answers (3)

JeanLColombo
JeanLColombo

Reputation: 160

You can find the index of your round-down breakpoint array using System.Linq.

var index = breakpoint.Where(i => i <= totalValue).ToList().Count - 1;

This line of code will select all itens within your array lower than totalValue, put into a list, and count it's entry. To get the index, just subtract 1 from it.

This solution assumes all entries in breakpoint are in ascending order.

It is the simplest solution I can think of, but it might be computationally expesive, due to searching the whole array.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460158

You can use Array.BinarySearch which gives you all you need to know:

public static int GetNearestIndex<T>(T[] items, T value)
{
    int index = Array.BinarySearch(items, value);
    if(index >= 0) 
        return index;
    if(index == -1)
        return 0; // is lower than first, so maybe you want to return -1
    return ~index - 1;
}

I'm using the bitwise complement operator to determine the correct index.

.Net Fiddle with some edge cases.

Upvotes: 2

Charlieface
Charlieface

Reputation: 71668

A naive implementation may be good enough

valueDisplayed = breakpoint[Array.FindIndex(breakpoint, v => v > totalValue) - 1];

But you may want to do binary search to speed it up

Upvotes: 1

Related Questions