What is the most effective method for performing a series of j
operations on an array of integers, where j
can range from being fewer or equal to as long as the array itself?
I attempted the following approach...
function performJ(arr, j) {
arr.sort((a, b) => b - a);
let i = 0;
while (j !== 0) {
if (i < arr.length) {
arr[i] = Math.ceil(arr[i] / 2)
} else {
// when i reaches arr.length, reset it to continue operations j
i = 0;
arr[i] = Math.ceil(arr[i] / 2)
}
// increment i, step through arr
++i;
// decrement j as we perform operations on arr
--j;
}
return arr.reduce((a, b) => a + b);
}
While this solution works for many cases, it seems that with larger inputs for both arr
and j
, the arithmetic calculations within the while
loop go awry.
Thank you!
EDIT: Revised question for better understanding. I had a previous solution that functioned correctly but was too slow. Although the arithmetic in this revised solution may be inaccurate at times, it performs significantly faster.