不用Math.min,用for循环与函数求二维表格最小值的优化问询
寻找最小自然情境下的最小值及对应选项的更简洁实现
给定如下二维表格数据,要求不使用Math.min方法,仅通过for循环与函数实现,找到最小自然情境下的最小值及对应选项。我已经写出了实现代码,想问问有没有更简洁的写法。
| N1 | N2 | N3 | |
|---|---|---|---|
| option 1 | 10 | 20 | 30 |
| option 2 | 40 | 50 | 60 |
| option 3 | 70 | 80 | 90 |
| option 4 | 100 | 110 | 120 |
我的实现代码:
const strategyTable = [ [10, 20, 30], [40, 50, 60], [70, 80, 90], [100, 110, 120] ]; function findLowestDecisionAndLowestValue(strategyTable) { let lowestDecision = 1; let lowestValue = strategyTable[0][0]; for (let i = 0; i < strategyTable[0].length; i++) { let columnMinimum = strategyTable[0][i]; for (let j = 0; j < strategyTable.length; j++) { if (strategyTable[j][i] < columnMinimum) { columnMinimum = strategyTable[j][i]; } } if (columnMinimum < lowestValue) { lowestValue = columnMinimum; lowestDecision = i + 1; } } return { lowestDecision, lowestValue }; } let { lowestDecision, lowestValue } = findLowestDecisionAndLowestValue(strategyTable); console.log("Lowest value: " + lowestValue); console.log("Lowest decision Option " + lowestDecision);
可以通过合并循环逻辑简化代码,不需要先单独计算每列最小值再比较。直接遍历所有元素的同时跟踪全局最小值及其对应选项,减少一层循环嵌套,让逻辑更紧凑:
const strategyTable = [ [10, 20, 30], [40, 50, 60], [70, 80, 90], [100, 110, 120] ]; function findLowestDecisionAndLowestValue(table) { let lowestValue = table[0][0]; let lowestDecision = 1; // 遍历每一列 for (let col = 0; col < table[0].length; col++) { // 遍历当前列的每一行,直接更新全局最小值 for (let row = 0; row < table.length; row++) { const currentVal = table[row][col]; if (currentVal < lowestValue) { lowestValue = currentVal; lowestDecision = col + 1; } } } return { lowestDecision, lowestValue }; } const result = findLowestDecisionAndLowestValue(strategyTable); console.log(`Lowest value: ${result.lowestValue}`); console.log(`Lowest decision Option ${result.lowestDecision}`);
另外,也可以用**数组遍历方法(forEach)**替代for循环,代码可读性更强,同时依然符合不使用Math.min的要求:
const strategyTable = [ [10, 20, 30], [40, 50, 60], [70, 80, 90], [100, 110, 120] ]; function findLowestDecisionAndLowestValue(table) { let lowestValue = table[0][0]; let lowestDecision = 1; table[0].forEach((_, colIndex) => { table.forEach(row => { const val = row[colIndex]; if (val < lowestValue) { lowestValue = val; lowestDecision = colIndex + 1; } }); }); return { lowestDecision, lowestValue }; } const result = findLowestDecisionAndLowestValue(strategyTable); console.log(`Lowest value: ${result.lowestValue}`); console.log(`Lowest decision Option ${result.lowestDecision}`);
这两种写法都去掉了中间变量(如原代码中的columnMinimum),逻辑更直接,代码更简洁,同时保持了纯循环/函数实现的要求,未使用Math.min方法。
内容的提问来源于stack exchange,提问作者nowayredditisbetter
相关产品推荐
相关产品推荐

