我试着用香草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数组以确定需要哪些权重?
发布于 2019-02-25 17:05:25
下面我有一个简单的解决方案,如果目标重量的值总是可用板块的总和。假设权重数组按降序排序。我循环考虑了所有可用的权重,只有当总重量超过所需的总重量时,才会继续进行下一个重量。
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]发布于 2019-02-25 17:08:41
对此的一个可能的解决方案是无限期地迭代,直到
在每一个迭代步骤中,您都会减去最高的权重乘以最高的可能因子,将两者存储在一个合适的数据结构中(我的实现只是使用一个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
这个问题本质上是背包问题的一个实例。
注意,我们假设plates是排序的。否则,Array.find将不一定检索可以从总权重中减去的最大权重。
发布于 2019-02-25 17:03:21
这里有个解决办法。如果可用的板块不能与目标重量相加,它将返回与目标最接近的可用板块的组合。改编自这个答案。
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]);
}https://stackoverflow.com/questions/54870802
复制相似问题