[英]How do I make a loop for this in a way that it finishes each of the if statement before going to the next?
What I am trying to do is find if the finalWeight is divisible by 45 if so I add it into the array actualWeights then subtract the finalWeight by 45 and go on till it is no longer divisible by 45. Then goes to 25, 5 and 2.5.我想要做的是找到 finalWeight 是否可以被 45 整除,如果是这样我将它添加到数组中 actualWeights 然后将 finalWeight 减去 45 和 go 直到它不再被 45 整除。然后转到 25、5 和 2.5 . I just don't know how to make the loop in a way that it finishes all of 45 and then goes to the next if statement.我只是不知道如何以完成所有 45 个循环然后进入下一个 if 语句的方式进行循环。
if(Math.floor(finalWeight/45)){
actualWeights.push(45);
finalWeight -= 45;
}else if(Math.floor(finalWeight/25)){
actualWeights.push(25)
finalWeight -= 25;
}else if(Math.floor(finalWeight/10)){
actualWeights.push(10)
finalWeight -= 10;
}else if(Math.floor(finalWeight/5)){
actualWeights.push(5)
finalWeight -= 5;
}else if(Math.floor(finalWeight/2.5)){
actualWeights.push(2.5)
finalWeight -= 2.5;
}
Based on your description you want a greedy algorithm, which won't always produce an option with the least number of, in this case, weights.根据您的描述,您需要一个贪心算法,在这种情况下,它不会总是产生一个权重最少的选项。
To make this code DRY, we can simplify this to take in an array of weights available.为了使这段代码干燥,我们可以简化它以获取可用的权重数组。
const calculateWeights = (targetWeight, validWeights) => validWeights.reduce((ret, weight) => { ret.weights = ret.weights.concat( new Array(Math.floor(ret.remainingWeight / weight)).fill(weight) ); ret.remainingWeight %= weight; return ret; }, { remainingWeight: targetWeight, weights: [] }).weights; const finalWeight = 115; const validWeights = [45, 25, 10, 5, 2.5]; const weights = calculateWeights(finalWeight, validWeights); console.log(weights);
another way to write this, without reduce or new Array(size).fill(value)
, is this不用 reduce 或new Array(size).fill(value)
的另一种写法是这样
const calculateWeights = (targetWeight, validWeights) => { const weights = []; let remainingWeight = targetWeight; // not needed, you can subtract from `targetWeight` itself since it's a copy, but usually you shouldn't modifiy inputs. for (const weight of validWeights) { while (remainingWeight >= weight) { weights.push(weight); remainingWeight -= weight; } } return weights; }; const finalWeight = 115; const validWeights = [45, 25, 10, 5, 2.5]; const weights = calculateWeights(finalWeight, validWeights); console.log(weights);
Pick whichever makes more sense/is more readable to you and others.选择对你和其他人更有意义/更易读的那个。 If performance becomes an issue, then see which is faster.如果性能成为问题,那么看看哪个更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.