简体   繁体   English

如果是平局,如何在javascript中返回较小的数字?

[英]In the case of a tie, how do I return the smaller number in javascript?

I need to write a function that takes two inputs, 'target' (integer) and 'values' (a list of integers), and find which number in 'values' is closest to 'target'. 我需要编写一个接受两个输入的函数,即“目标”(整数)和“值”(整数列表),并找出“值”中的哪个数字最接近“目标”。 I came up with the following: 我想出了以下几点:

var targetNum = 0;
var valuesArr = [2, 4, 6, 8, 10];

function closestToTarget(target, values) {
    var currVal = values[0];
    var diff = Math.abs(target - currVal);
    for (var i = 0; i < values.length; i++) {
        var currDiff = Math.abs(target - values[i]);
        if (currDiff < diff) {
            diff = currDiff;
            currVal = values[i];
        }
    }
    return currVal;
}
alert(closestToTarget(targetNum, valuesArr));

The function works, but I'm unable to return the smaller value in the case of a tie. 该函数有效,但是如果出现平局,我将无法返回较小的值。 The best that I could think of was the following which did not work: 我能想到的最好的是以下无效的方法:

function closestToTarget(target, values) {
    var currVal = values[0];
    var diff = Math.abs(target - currVal);
    for (var i = 0; i < values.length; i++) {
        var currDiff = Math.abs(target - values[i]);
        if (currDiff < diff) {
            diff = currDiff;
            currVal = values[i];
        }
        else if (currDiff == diff) {
            return Math.min[currVal, values[i]];
        }
        else {
            return currVal[i - 1];
        }
    }
    return currVal;
}

In the case of a tie, how do I return the smaller number in JavaScript? 如果是平局,如何在JavaScript中返回较小的数字?

Your code looks like it would work try changing Math.min[currVal, values[i]] to Math.min(currVal, values[i]) that should work if your values are ordered (simple syntax issue). 您的代码看起来像尝试将Math.min[currVal, values[i]]更改为Math.min(currVal, values[i])可以正常工作,如果您的值是有序的(简单的语法问题)。

As kojow7 mentioned, the first function should also work as long as the values are ordered. 正如kojow7所提到的,只要对values进行排序,第一个函数也应该起作用。

Otherwise instead of return Math.min(...) you should try to do currVal = Math.min(...) and keep iterating and then returning the currVal after the loop. 否则,您应该尝试执行currVal = Math.min(...)并保持迭代,然后在循环后返回currVal ,而不是return Math.min(...) This just makes sure that you check every value in the values array to make sure that you haven't missed anything (but if it's ordered, then there's no need to keep checking because the difference will only incraese). 这只是确保您检查values数组中的每个值以确保您没有遗漏任何东西(但是如果已订购,则无需继续检查,因为差异只会增加)。

Apart from the syntax error (missing parentheses) you could use some ES6 syntax to write a more concise function: 除了语法错误(缺少括号)之外,您还可以使用一些ES6语法编写更简洁的函数:

 function closestToTarget(target, values) { const m = Math.min(...values.map( v => Math.abs(target - v))); return Math.min(...values.filter( v => Math.abs(target - v) === m )); } var valuesArr = [2, 4, 6, 8, 10]; // Try several numbers for (var i = 1; i < 12; i++) { console.log(i, closestToTarget(i, valuesArr)); } 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The trick is that when you find a new best difference, as well as recording the difference ( bestDiff ), you also record the value that caused that difference ( bestVal ). 诀窍在于,当您发现新的最佳差异并记录差异( bestDiff )时,您还记录了导致该差异的值( bestVal )。

So now, if you encounter a tie ( currDiff == bestDiff ), you need to check if it's a better tie, that is, check if the current value is smaller than the recorded one ( currVal < bestVal ). 因此,现在,如果遇到平局( currDiff == bestDiff ),则需要检查它是否是更好的平局,即检查当前值是否小于记录的值( currVal < bestVal )。 If it is, then we update the best values (update both bestDiff and bestVal ). 如果是,那么我们将更新最佳值(同时更新bestDiffbestVal )。

function closestToTarget(target, values) {
    var currVal = values[0];
    var bestDiff = Math.abs(target - currVal);
    var bestVal = currVal;

    for (var i = 1; i < values.length; i++) {
        var currVal = values[i];
        var currDiff = Math.abs(target - values[i]);
        if (currDiff < bestDiff || (currDiff == bestDiff && currVal < bestVal)) {
            bestDiff = currDiff;
            bestVal = currVal;
        }
    }
    return bestVal;
}

Examples: 例子:

closestToTarget(2,[2,4,6,8,10]) // 2
closestToTarget(2,[10,8,6,4,2]) // 2
closestToTarget(3,[10,8,6,4,2]) // 2

Your idea should work, but you could also use your first function but with the addition of something that checks for a lower tie at the end: 您的想法应该可行,但您也可以使用第一个功能,但要添加一些可以在最后检查平局的东西:

function closestToTarget(target, values) {
    var currVal = values[0];
    var diff = Math.abs(target - currVal);
    for (var i = 0; i < values.length; i++) {
        var currDiff = Math.abs(target - values[i]);
        if (currDiff < diff) {
            diff = currDiff;
            currVal = values[i];
        }
    }

    // We found the closest but now check if there's a smaller tie
    if (currVal > target && values.indexOf(target - diff) > -1 ) {
        return target - diff;
    }
    else {
    // if not just return what we originally found
        return currVal;
    }
}

https://jsfiddle.net/vsj0q5u9/2/ https://jsfiddle.net/vsj0q5u9/2/

function findClosest(inpt, ar) {
   var minDiff = Math.abs(ar[0] - inpt);
   var res = ar[0];
   for (var i = 1; i < ar.length; i++) {
       if(Math.abs((ar[i] - inpt)) < minDiff)
           res = ar[i];
   }
   return res;
}

This is simple example on how to get the closest value in the array for the given input. 这是有关如何获取给定输入的数组中最接近的值的简单示例。 There will be no lower number to return in case of a tie. 如果打成平局,将没有较小的数字返回。 if you have more than one closest integer in the array the difference between your input is the same for all the cases of a tie. 如果数组中有多个最接近的整数,则在所有平局情况下,输入之间的差异相同。 so don't worry about it. 所以不用担心

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM