【问题标题】:Finding the index of lowest value, my assertion is failing找到最低值的索引,我的断言失败了
【发布时间】:2023-04-07 04:52:01
【问题描述】:

作业是:

完成函数indexOfMinimum的编写,该函数接受一个数组和一个数字startIndex,并返回出现在索引startIndex或更大的最小值的索引。如果这个最小值在这个范围内多次出现,则返回这个范围内最左边出现的索引。

这是我完成它的尝试

var indexOfMinimum = function(array, startIndex) {
    // Set initial values for minValue and minIndex,
    // based on the leftmost entry in the subarray:  
    var minValue = array[startIndex];
    var minIndex = startIndex;
    for (var i = minIndex + 1; i < array.length; i++) {
        if (array[i] < array[startIndex]) {
            minIndex = i;
            minValue = array[i];
        }
    }

    // Loop over items starting with startIndex, 
    // updating minValue and minIndex as needed:

    return minIndex;
};

var array = [18, 6, 66, 44, 9, 22, 14];
var index = indexOfMinimum(array, 2);

//  For the test array [18, 6, 66, 44, 9, 22, 14], 
//  the value 9 is the smallest of [..66, 44, 9, 22, 14]
//  Since 9 is at index 4 in the original array, 
//  "index" has value 4
println("The index of the minimum value of the subarray starting at index 2 is " + index + ".");
Program.assertEqual(index, 4);

最后的断言失败。根据我的逻辑,它返回 4 索引,但我认为它不能正常工作。为什么不呢?

【问题讨论】:

  • “插入声明”?那是什么说法?
  • Program.assertEqual(index, 4);这个
  • 到目前为止,找出此类问题为何不起作用的最佳方法是使用浏览器或 IDE 中内置的调试器。在函数的第一条语句上设置断点,运行代码,调试器将在该断点处停止。然后你可以逐步观察你的逻辑并检查你的变量。使用调试器不是高级技能;这基本上是您成功编写“Hello, world”后应该学习的第一件事。编码愉快!
  • 调试器怎么用,我不知道
  • @MuhammadHamza:搜索会发现很多有用的信息。对于 Chrome 的调试器:developers.google.com/web/tools/chrome-devtools

标签: javascript arrays selection-sort


【解决方案1】:

比较

if(array[i]<array[startIndex])

错了。你应该比较

if(array[i]<minValue)

...因为您想知道 array[i] 是否小于您目前找到的最小值,而不是小于您查看的第一个值。

有了这个改变,它就起作用了:

var indexOfMinimum = function(array, startIndex) {
// Set initial values for minValue and minIndex,
// based on the leftmost entry in the subarray:  
var minValue = array[startIndex];
var minIndex = startIndex;
for(var i = minIndex + 1 ; i < array.length ; i++)
{
    if(array[i]<minValue)
    {
        minIndex = i;
        minValue = array[i];
    }
}

// Loop over items starting with startIndex, 
// updating minValue and minIndex as needed:

return minIndex;
}; 

var array = [18, 6, 66, 44, 9, 22, 14];   
var index = indexOfMinimum(array, 2);

//  For the test array [18, 6, 66, 44, 9, 22, 14], 
//  the value 9 is the smallest of [..66, 44, 9, 22, 14]
//  Since 9 is at index 4 in the original array, 
//  "index" has value 4
console.log("The index of the minimum value of the subarray starting at index 2 is " + index + "."  );

(顺便说一句,空格并不邪恶。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 2014-09-23
    • 2017-12-09
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    相关资源
    最近更新 更多