Reputation: 525
I was doing Codeforces problem when I encountered a bug I don't actually know how to fix:
Problem:
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.
When I change an array (both inside and outside the while loop) automatically all the other array get changed too.
I don't really know what to try and how to fix it.
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]]));
Upvotes: 1
Views: 480
Reputation: 55740
Just clone the new_array
rather than using the same array to run operations as shift
mutates the original array.
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;
}
Upvotes: 1
Reputation: 448
Maybe this can fix.
function array_operation(array, start, end, value){
for (const i in array) if (i >= --start && i < end) array[i] += value;
return [...array];
}
Upvotes: 0