[英]How to find out how many times 3 values fit into one value with JavaScript
so I have the following constellation:所以我有以下星座:
There is a total number and I need to find out how many times the value X, Y and Z fit into it.有一个总数,我需要找出值 X、Y 和 Z 适合它的次数。 For example:
例如:
Total: 10.000 X: 5000 Y: 3000 Z: 1000总计:10.000 X:5000 Y:3000 Z:1000
The result should be: 1 times X 1 times Y 2 times Z结果应该是:1 times X 1 times Y 2 times Z
how can I calculate that with JS?我怎么用JS计算呢?
if (Total >= X) { numberOfX = Math.floor(Total / X); if (Total % X;== 0) { divisionRest = Total - (X * numberOfX). if (divisionRest >= Y) { numberOfY = Math.floor(divisionRest / Y) } } }
You can check how often the value fits in by您可以通过以下方式检查该值适合的频率
while(input >= 10000)
.while(input >= 10000)
的频率。 As long as it fits in increment your counter and subtract the value from the input input -= 10000
.input -= 10000
。 Because you have multiple values here to check you can use an array.因为这里有多个值要检查,所以可以使用数组。
Iterate over the array as long the current value fits in subtract it from the input and increment the counter.只要当前值适合,就迭代数组,从输入中减去它并递增计数器。
When it will not fit in anymore then go to your next value in the array and do the same with it as long as you have values in your array which are not >=
then your remaining input(After the substractions).当它不再适合时,go 到数组中的下一个值并对其执行相同操作,只要数组中的值不是
>=
那么剩余的输入(减法后)。
Here is the full code这是完整的代码
let values = [10000, 5000, 3000, 1000]; let input = 508000; let result = []; for (let i = 0; i < values.length; i++) { let counter = 0; while (input >= values[i]) { counter++; input -= values[i]; } result.push({ "number": values[i], "counter": counter }); } console.log(result);
I know that there already is an answer, however I wanted to point out that you can do the same thing in a more concise way:我知道已经有了答案,但我想指出您可以用更简洁的方式做同样的事情:
var values = [10000, 5000, 3000, 1000]; var input = 508000; var result = []; for (let i = 0; i < values.length; i++) { var counter = Math.floor(input / values[i]); input = input % values[i] result.push({ "number": values[i], "counter": counter }); } console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.