Assume we have an integer ‘x’ and ‘n’ possible values that ‘x’ can be mapped/binned to. What is an elegant way in C to have a function that returns the closest ‘nth’ value to x?
Pseudo code example;
int x = 40;
int res;
int bins[] = { 0, 20, 80, 200 }; /* Sorting is guaranteed */
res = int_bin(x, bins);
assert(res == 20); /* 40 is closer to 20 than 80 */
x = 150;
res = int_bin(x, bins);
assert(res == 200); /* 150 is closer to 200 than 80 */
By elegant I mean not just a bunch of if/else if/else statements.
If the list is sorted, then you can simply do a binary search for the value.
If the search does not find the value in the list, you will know at what index the value would have been located had it been in the list. Then, you can then compare the value against the element at that index and the element at the previous index (if the index isn’t zero, obviously) and see which is closer.