gpt4 book ai didi

Javascript 数组错误 - 通过更改一个数组,所有其他数组都会更改

转载 作者:行者123 更新时间:2023-12-02 20:50:17 24 4
gpt4 key购买 nike

我在做 Codeforces 问题时遇到了一个我实际上不知道如何修复的错误:

问题:

Vasya has invented a new hash function of an array. It is calculated as follows. While the array has at least two elements, the first two elements, call them 𝑎1 and 𝑎2, are deleted, and the new element 𝑎2−𝑎1 is inserted to the beginning of the array. When the array has only one element, this number is a value of Vasya's hash function of this array.

Vasya has the array 𝑎1 , 𝑎2,..., 𝑎𝑛. He performs 𝑞 operations of the following form: "increase all elements in the segment [𝑙𝑗,𝑟𝑗] by 𝑣𝑗". After each operation he wants to know the value of Vasya's hash function of this array.

Input: The first line contains an integer 𝑛(1≤𝑛≤500000) — the size of the array. The second line contains 𝑛 integers 𝑎𝑖 (−109≤𝑎𝑖≤109) — the elements of the array. The third line contains an integer 𝑞 (1≤𝑞≤200000) — the number of operations. Each of the next 𝑞 lines contains three integers 𝑙𝑗, 𝑟𝑗, 𝑣𝑗 (1≤𝑙𝑗≤𝑟𝑗≤𝑛, −109≤𝑣𝑗≤109) — the parameters of the 𝑗-th operation.

Output: Output 𝑞 lines. In the 𝑗-th line output one integer — the value of Vasya's hash function after the 𝑗-th operation.

当我更改一个数组(在 while 循环内部和外部)时,所有其他数组也会自动更改。

我真的不知道该尝试什么以及如何解决它。

function hash(n, inputArray, q, operations){

let result = [];

for (const operation of operations) {
let new_array = array_operation(inputArray, operation[0], operation[1], operation[2]);

while (new_array.length >= 2) {
let new_value = new_array.shift() + new_array.shift();
new_array.unshift(new_value);
}

result.push(new_array.shift());
}
return result;
}

function array_operation(array, start, end, value){
for (const i in array) if (i >= --start && i < end) array[i] += value;
return array;
}

console.log(hash(7, [4, 2, -5, 10, 4, -2, 6], 2, [[2, 4, -8,], [5, 7, 2], [3, 3, -1], [3, 7, 3]]));

最佳答案

只需克隆 new_array 而不是使用相同的数组来运行操作,因为 shift 会改变原始数组。

function array_operation(array, start, end, value) {
let cloned_array = [...array];

for (const i in cloned_array) {
if (i >= --start && i < end) {
cloned_array[i] += value;
}
}

return array;
}

关于Javascript 数组错误 - 通过更改一个数组,所有其他数组都会更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61619713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com