如何在数组中的值之前和之后添加值 [英] How to add a value in an array to the values before and after it
本文介绍了如何在数组中的值之前和之后添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将数字数组转换为非零整数元素的值的步长,即
I am trying to turn an array of numbers into steps of the value of the Non-Zero integer element i.e
spread([0,0,n,0,0] returns =>
[0 + n-2, 0 + n-1, n, 0 + n -1, 0 + n - 2]
spread([0,0,0,n,0,2]) returns =>
[0+n-3, 0+n-2, 0+n-1, n ,(2-1)+(n-1) ,2 + n-2]
spread([0,0,0,4,0,0,0]) returns => [1,2,3,4,3,2,1]
spread([0,0,0,3,0,2,0]) returns => [0,1,2,3,3,3,1]
spread([3,0,0,0]) returns => [3,2,1,0]
等。
我尝试了传统的for循环,我尝试了forEach,甚至是array.map,但没有按预期工作
I have tried the traditional for loop, i have tried forEach, even array.map but nothing works as expected
这是我尝试过的方法,但不起作用
Here is what I tried but it doesn't work
function pop(balloon) {
let res = [];
for (let i = 0; i < balloon.length; i++) {
let n = balloon[i];
let before = balloon[i - 1];
let after = balloon[i + 1];
if (n !== 0 && i < balloon.length - 1) {
res.push(before + n - 1);
res.push(n);
res.push(after + n - 1);
} else {
res.push(n);
}
}
return res;
}
const array1 = [0, 0, 0, 0, 4, 0, 0, 3, 0]
const array2 = [0, 0, 2, 0, 0]
console.log(pop(array1)) // returns[0, 0, 0, 0, 3, 4, 3, 0, 0, 2, 3, 2, 0]
// expected output => [0, 1, 2, 3, 4, 4, 4, 4, 2]
console.log(pop(array2)) // returns[0, 0, 1, 2, 1, 0, 0]
// expected output => [0, 1, 2, 1, 0]
推荐答案
您可以通过使用数组的副本来缩小数组,并使用递归函数左右移动该递归函数,以检查要散布的值和索引。
You could reduce the array by using a copy of the array and go left and right with a recursive function which checks the value to spread and the index.
function spread(array) {
return array.reduce((r, v, i, a) => {
const
iter = (v, i, d) => {
if (v < 1 || !(i in a)) return;
r[i] += v;
iter(v - 1, i + d, d);
};
iter(v - 1, i - 1, -1);
iter(v - 1, i + 1, 1);
return r;
}, array.slice());
}
console.log(...spread([0, 0, 0, 4, 0, 0, 0])); // [1, 2, 3, 4, 3, 2, 1]
console.log(...spread([0, 0, 0, 3, 0, 2, 0])); // [0, 1, 2, 3, 3, 3, 1]
console.log(...spread([3, 0, 0, 0])); // [3, 2, 1, 0]
function spread(array) {
const dec = v => Math.max(v - 1, 0);
var result = array.slice(),
temp = array.slice(1).map(v => Math.max(v - 1, 0)),
offset;
while (temp.length) {
temp.forEach((v, i) => result[i] += v);
temp = temp.slice(1).map(dec);
}
temp = array.slice(0, -1).map(dec);
while (temp.length) {
offset = result.length - temp.length;
temp.forEach((v, i) => result[i + offset] += v);
temp = temp.slice(0, -1).map(dec);
}
return result;
}
console.log(...spread([0, 0, 0, 4, 0, 0, 0])); // [1, 2, 3, 4, 3, 2, 1]
console.log(...spread([0, 0, 0, 3, 0, 2, 0])); // [0, 1, 2, 3, 3, 3, 1]
console.log(...spread([3, 0, 0, 0])); // [3, 2, 1, 0]
这篇关于如何在数组中的值之前和之后添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文