最近获得了数阵 [英] get closest number out of array

查看:138
本文介绍了最近获得了数阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从负1000至1000加一个数字,我在它的数字数组。像这样的:

I have a number from minus 1000 to plus 1000 and I have an array with numbers in it. Like this:

[2, 42, 82, 122, 162, 202, 242, 282, 322, 362]

我想这个数字我已经得到改变阵列的最接近的数字。

I want that the number I've got changes to the nearest number of the array.

例如,我得到 80 的号码,我想让它变得 82

For example I get 80 as number I want it to get 82.

推荐答案

下面是伪code应该兑换成任何过程语言:

Here's the pseudo-code which should be convertible into any procedural language:

array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
number = 112
print closest (number, array)

def closest (num, arr):
    curr = arr[0]
    foreach val in arr:
        if abs (num - val) < abs (num - curr):
            curr = val
    return curr

它只是作品出给定数量和每个数组元素之间的绝对差值,让您回来的最小差异的一个。

It simply works out the absolute differences between the given number and each array element and gives you back one of the ones with the minimal difference.

有关示例值:

number = 112  112  112  112  112  112  112  112  112  112
array  =   2   42   82  122  162  202  242  282  322  362
diff   = 110   70   30   10   50   90  130  170  210  250
                         |
                         +-- one with minimal absolute difference.

作为一个概念证明,这里的Python的code我用行动来证明这一点:

As a proof of concept, here's the Python code I used to show this in action:

def closest (num, arr):
    curr = arr[0]
    for index in range (len (arr)):
        if abs (num - arr[index]) < abs (num - curr):
            curr = arr[index]
    return curr

array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
number = 112
print closest (number, array)


而且,如果你的真正的需要在Javascript,请参见下面的完整的HTML文件,以实际行动体现功能:


And, if you really need it in Javascript, see below for a complete HTML file which demonstrates the function in action:

<html>
    <head></head>
    <body>
        <script language="javascript">
            function closest (num, arr) {
                var curr = arr[0];
                var diff = Math.abs (num - curr);
                for (var val = 0; val < arr.length; val++) {
                    var newdiff = Math.abs (num - arr[val]);
                    if (newdiff < diff) {
                        diff = newdiff;
                        curr = arr[val];
                    }
                }
                return curr;
            }
            array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
            number = 112;
            alert (closest (number, array));
        </script>
    </body>
</html>


现在记住有可能是提高效率的范围,如果,例如,您的数据项进行排序(即可以从样本数据中推断出来,但你不明确说明的话)。你可以,例如,使用二进制搜索找到最接近的项目。


Now keep in mind there may be scope for improved efficiency if, for example, your data items are sorted (that could be inferred from the sample data but you don't explicitly state it). You could, for example, use a binary search to find the closest item.

您也应该记住,除非你需要做的许多的每秒次,效率的提高将主要容易被忽视的,除非你的数据集获得的的较大

You should also keep in mind that, unless you need to do it many times per second, the efficiency improvements will be mostly unnoticable unless your data sets get much larger.

如果您的的想尝试一下这种方式(并能保证数组按升序排序),这是一个很好的起点:

If you do want to try it that way (and can guarantee the array is sorted in ascending order), this is a good starting point:

<html>
    <head></head>
    <body>
        <script language="javascript">
            function closest (num, arr) {
                var mid;
                var lo = 0;
                var hi = arr.length - 1;
                while (hi - lo > 1) {
                    mid = Math.floor ((lo + hi) / 2);
                    if (arr[mid] < num) {
                        lo = mid;
                    } else {
                        hi = mid;
                    }
                }
                if (num - arr[lo] <= arr[hi] - num) {
                    return arr[lo];
                }
                return arr[hi];
            }
            array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
            number = 112;
            alert (closest (number, array));
        </script>
    </body>
</html>

基本上,它使用包围和中间值的检查降低了一半解空间的每一次迭代,经典 O(日志N)算法,而上面的顺序搜索是 O(N)

It basically uses bracketing and checking of the middle value to reduce the solution space by half for each iteration, a classic O(log N) algorithm whereas the sequential search above was O(N):

2 42 82 122 162 202 242 282 322 362
L             M                   H  L=0, H=9, M=4, 162 higher, H<-M
L     M       H                      L=0, H=4, M=2, 82 lower/equal, L<-M
      L   M   H                      L=2, H=4, M=3, 122 higher, H<-M
      L   H                          L=2, H=3, difference of 1 so exit
          ^
          |
          H (122-112=10) is closer than L (112-82=30) so choose H

如前所述,应该没有太大的差别对于小型数据集或东西,不要的需求的是瞬息万变的,但它是你可能要考虑的选项。

As stated, that shouldn't make much of a difference for small datasets or for things that don't need to be blindingly fast, but it's an option you may want to consider.

这篇关于最近获得了数阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆