【问题标题】:How to loop through an array of numbers to see which numbers are relevant to another number?如何遍历一个数字数组以查看哪些数字与另一个数字相关?
【发布时间】:2019-02-25 16:36:21
【问题描述】:

我正在尝试用原生 JavaScript 编写一个简单的举重程序。用户输入一定量的重量,它会返回特定的重量板放在杠铃的每一侧。

然后我将这个数字带入一个函数,从它减去 45 来计算杠铃重量,然后将该数字除以 2,即放置在杠铃每一侧的重量。

const num = document.getElementById("weightAmount").value;

function getWeightAmount (num) {
const newNum = num - 45;
const halfNum = newNum / 2;
return getWeights(halfNum);
}

每个重量板都有一个数组:

let plates = [44, 33, 22, 11, 5.5, 2.75];

我无法正确循环遍历数组以获取我想要的内容。如果我需要每边 60.5 磅,它应该返回 44、11、5.5。所以我需要弄清楚plate 数组中的哪些数字适合我的第一个函数返回的数字。

我有一个名为 weights 的空数组,我想将 plates 数组中的数字推送到该工作中,然后返回权重。

我的问题是如何循环遍历plates 数组以确定需要哪些权重?

【问题讨论】:

  • 找到只除一次目标重量的重量,把它加到杠铃上,然后从目标重量中减去。重复直到目标体重为零。
  • 您使用plates.forEach(function(plate){}} 循环遍历数组以获取for (let plate of plates) {}
  • 可能相关:Knapsack problem
  • 嗯,正如@FK82 提到的,它是背包,但稍作修改。其实就是一个Change-making问题的修改版[en.wikipedia.org/wiki/Change-making_problem],它本身就是一个背包问题的修改版。
  • @Taylorg:您可以在伪多项式时间内使用动态规划按照下面给出的答案编写自己的解决方案,也可以直接使用下面给出的解决方案

标签: javascript arrays loops for-loop


【解决方案1】:

一个可能的解决方案是无限期地迭代,直到任一

  • 您有解决方案
  • 给定一组权重,问题变得无法解决

每个迭代步骤,您减去可能的最高权重乘以可能的最高因子,将两者存储在合适的数据结构中(我的实现只是使用Object)并继续。

const plates = [44, 33, 22, 11, 5.5, 2.75];

// We assume that plates is always sorted
const determineWeights = (totalWeight) => {
  let factor = 0;
  let weights = {};

  while (totalWeight > 0) {
    weight = plates.find(weight => Math.floor(totalWeight / weight) > 0);

    // There is no weight we can subtract from the total weight to solve the problem
    // Hence, the problem is unsolvable and we return null to indicate that no solution exists
    if (!weight) { return null; }

    // Determine the factor with which to multiply the weight before we subtract from the total weight an subtract the product
    factor = Math.floor(totalWeight / weight);
    totalWeight = totalWeight - factor * weight;

    // Store weight and factor
    weights[weight] = factor;
  }
  
  return weights;
}


console.log(determineWeights(104.5)); // { "11": 1, "44": 2, "5.5": 1 }
console.log(determineWeights(60.5)); // { "11": 1, "44": 1, "5.5": 1 }
console.log(determineWeights(5.0)); // null

问题本质上是Knapsack problem 的一个实例。

请注意,我们假设 plates 已排序。否则,Array.find 不一定会检索到可以从总重量中减去的最大重量。

【讨论】:

    【解决方案2】:

    如果目标重量的值始终是可用盘子的总和,我有一个简单的解决方案。假设权重数组按降序排序。我循环考虑了所有可用的重量,并且只有在总重量超过您需要的总重量时才会继续下一个重量。

    function getWeights(targeWeight) {
    
        let plates = [44, 33, 22, 11, 5.5, 2.75];
    
        let totalWeight = 0;
    
        let neededPlates = [];
    
        let i = 0;
    
        while(i < plates.length){
    
            var pweight = totalWeight + plates[i];
    
            if (pweight > targeWeight) {
                i++;
                continue;
            }
    
            totalWeight += plates[i];
            neededPlates.push(plates[i]);
        }
    
        return neededPlates;
    }
    
    console.log(getWeights(60.5)); // [44, 11, 5.5]
    console.log(getWeights(104.5)); //[44, 44, 11, 5.5]
    

    【讨论】:

    • 完美运行!谢谢!
    【解决方案3】:

    这里有一个解决方案。如果可用板加起来不等于目标重量,它将返回加起来最接近目标的可用板的组合。改编自this answer

    function createSubsets(numbers, target) {
        // filter out all items larger than target
        numbers = numbers.filter(function (value) {
            return value <= target;
        });
    
        // sort from largest to smallest
        numbers.sort(function (a, b) {
            return b - a;
        });
    
        var i;
        var sum = 0;
        var addedIndices = [];
    
        // go from the largest to the smallest number and
        // add as many of them as long as the sum isn't above target
        for (i = 0; i < numbers.length; i++) {
            if (sum + numbers[i] <= target) {
                sum += numbers[i];
                addedIndices.push(i);
            }
        }
    
        return addedIndices.map(n => numbers[n]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 2016-10-02
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      相关资源
      最近更新 更多