如何确定两个比数组中的其他数字更接近的数字 [英] How can I determine two numbers that are more close than others in an array

查看:255
本文介绍了如何确定两个比数组中的其他数字更接近的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数组:

$arr = array (20, 1, 5, 10, 7, 16);

我想获得57.因为它们比其他项目更接近彼此.换句话说,它们之间的差异是最低的数字:

I would like to get 5 and 7. Because these are more close to each other than other items. In other word the difference between them is the lowest number:

7 - 5 = 2 // 2 is lowest number as the difference between all array's items

我该怎么办?

$keep = $arr[0];
$diff = $arr[1] - $arr[0];
foreach ($arr as $item) {
    if ( ($keep - $item) < $diff && $keep != $item ) {
        $diff = $item;
    }
}

我的代码不完整,因为它只是将第一项与其他项进行比较.

My code is incomplete, Because it just compares first item with other items.

推荐答案

说明

因此,要获取数组中最接近的两个数字,必须将每个值彼此比较.但是您不必将它们与自己以及已经比较过的以前的对象进行比较.

Explanation

So to get the two numbers in an array which are the closest to each other you have to compare each value with each other value. But you don't have to compare them with themselves and to the previous ones which you already compared.

要计算多少次比较,可以使用二项式系数:

To calculate how many comparisons you have to do you can use the binomial coefficient:

(n)            n!
(k)   →   ─────────────
          k! * (n - k)!

其中n是元素总数,k是您选择的数量

在您的示例中,这意味着:

And in your example this would mean:

n = 6 //Array elements
k = 2 //Two values which you compare

     6!                  720
─────────────   →   ─────────────   = 15 comparison
2! * (6 - 2)!          2  *  24

可视化

20 , 1 , 5 , 10 , 7 , 16  //Array values
↓    ↑   ↑   ↑    ↑   ↑
└────┴───┴───┴────┴───┘  //20 compared to all values, except itself
     ↓   ↑   ↑    ↑   ↑
     └───┴───┴────┴───┘  //1  compared to all values, except itself + [20]
         ↓   ↑    ↑   ↑
         └───┴────┴───┘  //5  compared to all values, except itself + [20, 1]
             ↓    ↑   ↑
             └────┴───┘  //10 compared to all values, except itself + [20, 1, 5]
                  ↓   ↑
                  └───┘  //7  compared to all values, except itself + [20, 1, 5, 10]

                         //16 compared to all values, except itself + [20, 1, 5, 10, 7]

现在要在代码中执行此操作,我们需要2个循环来循环遍历整个数组,以获取第一个循环的每个值.但是,正如我们已经说过的,我们可以忽略值本身和之前的值,因此为此我们将2用于循环并将内部循环的键设置为外部键+ 1.

Now to do this in code we need 2 loops to loop over the entire array for each value of the first loop. But as we already said we can ignore the value itself and the previous values, so for this we use 2 for loops and set the key, for the inner loop, to be the outer key + 1.

for($key = 0, $length = count($arr); $key < $length; $key++){          
    for($innerKey = $key + 1; $innerKey < $length; $innerKey++){
      //↑ Skipping the previous values and the value itself    
    }               
}

在内部循环本身中,我们只需要访问外部循环的当前值,并获得与内部循环的值相比的差.对于负数也可以使用,我们只需将其包装到abs()调用中,以使差异始终为正.

In the inner loop itself we just need to access the current value of the outer loop and get the difference compared to the value of the inner loop. That this also works with negative numbers we just wrap it into an abs() call to make the difference always positive.

然后,我们仅检查差异是否小于保存在$nearest中的最小差异. (我们通过数组的最大值和最小值之差+ 1来初始化$nearest):

Then we just check if the difference is smaller than the smallest difference which we already found, saved in $nearest. (We initialized $nearest by the difference of the biggest and smallest value of the array + 1):

if( ($diff = abs($arr[$keys[$key]] - $arr[$keys[$innerKey]])) < $nearest)          

如果差异小于我们已经找到的最小差异,则将两个值写入数组并设置新的最小差异:

If the difference is smaller than the smallest difference which we already found, we write the two values into an array and set the new smallest difference:

$result = [$arr[$keys[$key]], $arr[$keys[$innerKey]]];
$nearest = $diff;

代码

<?php

    $arr = [20, 1, 5, 10, 7, 16];

    $keys = array_keys($arr);
    $nearest = max($arr) - min($arr) + 1;
    $result = [];

    for($key = 0, $length = count($arr); $key < $length; $key++){

        for($innerKey = $key + 1; $innerKey < $length; $innerKey++){

            if( ($diff = abs($arr[$keys[$key]] - $arr[$keys[$innerKey]])) < $nearest){
                $result = [$arr[$keys[$key]], $arr[$keys[$innerKey]]];
                $nearest = $diff;

            }

        }

    }

    print_r($result);

?>

输出

[5, 7]

这篇关于如何确定两个比数组中的其他数字更接近的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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