Mar*_*cki 2 javascript arrays algorithm sum
I need help with array sum algorithm, sum of result array values is never greater then limit, I have provided input => output bellow
I have tried something like this but It doesn't work properly for all tests in example
input
.map((x, i) => input
.slice(0, i + 1)
.reduce((prev, cur) => prev + cur, 0) > limit ? Math.max((x - (input.reduce((prev, cur) => prev + cur, 0) - limit)), 0) : x)Run Code Online (Sandbox Code Playgroud)
Example tests:
limit = 500
[0] => [0]
[300] => [300]
[600] => [500]
[0,1000] => [0, 500],
[600,300] => [500,0]
[500,0,0] => [500,0,0]
[400,200,0] => [400,100,0]
[0,200,300] => [0,200,300]
[0,600,300] => [0,500,0]
[0,0,600] => [0,0,500]
You can keep track of how much you have left, and use Math.min in your map callback:
let remaining = limit;
const result = array.map(value => {
value = Math.min(value, remaining);
remaining -= value;
return value;
});
Run Code Online (Sandbox Code Playgroud)
Live Example:
let remaining = limit;
const result = array.map(value => {
value = Math.min(value, remaining);
remaining -= value;
return value;
});
Run Code Online (Sandbox Code Playgroud)
function test(limit, array, expect) {
let remaining = limit;
const result = array.map(value => {
value = Math.min(value, remaining);
remaining -= value;
return value;
});
const good = result.every((value, index) => value === expect[index]);
console.log(array.join(","), result.join(","), good ? "OK" : "<== Error");
}
const limit = 500;
test(limit, [0], [0]);
test(limit, [300], [300]);
test(limit, [600], [500]);
test(limit, [0,1000], [0, 500]);
test(limit, [600,300], [500,0]);
test(limit, [500,0,0], [500,0,0]);
test(limit, [400,200,0], [400,100,0]);
test(limit, [0,200,300], [0,200,300]);
test(limit, [0,600,300], [0,500,0]);
test(limit, [0,0,600], [0,0,500]);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
101 次 |
| 最近记录: |