在平局的情况下,如何在javascript中返回较小的数字?

时间:2022-06-05 22:50:26

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:

我需要编写一个带有两个输入的函数,'target'(整数)和'values'(整数列表),并找出'values'中哪个数字最接近'target'。我想出了以下内容:

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中返回较小的数字?

5 个解决方案

#1


0  

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/

#2


1  

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所提到的,只要值被排序,第一个函数也应该起作用。

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. 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).

否则不要返回Math.min(...),你应该尝试做currVal = Math.min(...)并继续迭代,然后在循环后返回currVal。这只是确保你检查values数组中的每个值,以确保你没有遗漏任何东西(但如果它被订购,那么就没有必要继续检查,因为差异只会增加)。

#3


1  

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; }

#4


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). If it is, then we update the best values (update both bestDiff and bestVal).

所以现在,如果你遇到平局(currDiff == bestDiff),你需要检查它是否是一个更好的平局,即检查当前值是否小于记录的值(currVal )。如果是,那么我们更新最佳值(更新bestdiff和bestval)。

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

#5


0  

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.

这是关于如何为给定输入获取数组中最接近值的简单示例。如果出现平局,将不会返回较低的数字。如果数组中有多个最接近的整数,则输入之间的差异对于所有平局情况都是相同的。所以不要担心。

#1


0  

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/

#2


1  

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所提到的,只要值被排序,第一个函数也应该起作用。

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. 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).

否则不要返回Math.min(...),你应该尝试做currVal = Math.min(...)并继续迭代,然后在循环后返回currVal。这只是确保你检查values数组中的每个值,以确保你没有遗漏任何东西(但如果它被订购,那么就没有必要继续检查,因为差异只会增加)。

#3


1  

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; }

#4


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). If it is, then we update the best values (update both bestDiff and bestVal).

所以现在,如果你遇到平局(currDiff == bestDiff),你需要检查它是否是一个更好的平局,即检查当前值是否小于记录的值(currVal )。如果是,那么我们更新最佳值(更新bestdiff和bestval)。

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

#5


0  

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.

这是关于如何为给定输入获取数组中最接近值的简单示例。如果出现平局,将不会返回较低的数字。如果数组中有多个最接近的整数,则输入之间的差异对于所有平局情况都是相同的。所以不要担心。