You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不用Math.min,用for循环与函数求二维表格最小值的优化问询

寻找最小自然情境下的最小值及对应选项的更简洁实现

给定如下二维表格数据,要求不使用Math.min方法,仅通过for循环与函数实现,找到最小自然情境下的最小值及对应选项。我已经写出了实现代码,想问问有没有更简洁的写法。

N1N2N3
option 1102030
option 2405060
option 3708090
option 4100110120

我的实现代码:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 08:23:36