在 C 中将整数分类/映射到不同类别中的优雅方法是什么?
假设我们有一个整数“x”和“x”可以映射/合并到的“n”个可能值。在 C 中,有一个函数返回最接近 x 的“第 n”值的优雅方法是什么?
伪代码示例;
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 */
我所说的优雅不仅仅是一堆 if/else if/else 语句。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果列表已排序,那么您可以简单地对值进行二分搜索。
如果搜索未在列表中找到该值,您将知道如果该值位于列表中,该值将位于哪个索引处。然后,您可以将该值与该索引处的元素和前一个索引处的元素进行比较(显然,如果索引不为零),看看哪个更接近。
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.
不存储每个箱的中心值,而是存储每个箱周围的边界值。在数组的开头和结尾使用标记值以确保搜索始终找到答案。在您的示例中,将
{ 0, 20, 80, 200 }
替换为{ INT_MIN, 10, 50, 140, INT_MAX }
。如果实际问题像您的示例一样简单,您可以使用线性搜索。否则,二分查找是可行的方法。
Instead of storing the central value of each bin, store the boundary values around each bin. Use sentinel values at the beginning and end of the array to ensure that a search always finds an answer. In your example, replace
{ 0, 20, 80, 200 }
with{ INT_MIN, 10, 50, 140, INT_MAX }
.You can use a linear search if the real problem is as simple as your example. Otherwise, a binary search is the way to go.
在这里回答我自己的问题。
因为我想尽可能多地重用标准 C 函数。我不相信我可以使用 bsearch() 因为这不会给我任何关于如果找不到元素应该去哪里的索引的信息;我需要自己动手。
但是,如何在 bins[] 数组上使用 qsort() 并提供一个比较函数,该函数根据 bin 与“x”的接近程度进行排序,然后选择第 0 个元素作为我的答案?
Answering my own question here.
Since I'd like to reuse as much standard C functions as possible. I don't believe I can use bsearch() because that will give me no information as to the index of where the element should go if not found; I'd need to roll my own.
However, what about using
qsort()
on the bins[] array and give a comparison function that sorts based on how close the bin is to 'x' and then choosing the 0'th element as my answer?