-1

Let's say I have the following 2 Arrays:

let a = [5,5,5,5,0]
let b = [5,5,5,5,0]

Assuming that both arrays has the same length:

I want to get a value from an element of one Array and add the +1 itself and to other remaining elements. If the the picked value is still bigger than zero, then it should also continue adding it to elements of other array from starting index.

Example_1: If I pick a[2] then the outcome should be:

a = [5,5,1,6,1] // a[2] became 0 after picking 5, then in each remaining element we add +1 and continue to next array.
b = [6,6,5,5,0]

Example_2: Or If I pick b[3] from initial arrays, then the outcome should be:

a = [6,6,6,5,0] // b[3] became 0 after picking 5, then in each remaining element we add +1 and move to next array until our value becomes zero
b = [5,5,5,1,1]

Here is my attempt:

let pickedValue = a[2]

for (let index = 2; index < a.length; index++) {
    if (pickedValue > 0) {
        a[index] += 1
        pickedValue--
    }
}
for (let index = 0; index < pickedValue; index++) {
    if (pickedValue > 0) {
        b[index] += 1
        pickedValue--
    }
}

Can we do this in more dynamic way with maybe one loop?

Angels
  • 325
  • 4
  • 15

2 Answers2

1

You just need to iterate through both arrays. The chosen array should be iterated from the target + 1 up to its lenght, and the other array, from 0 up the target. You can see that I directly put a 1 to the chosen array at index target, instead of put a 0 and add +1.

(Also use some regex in order to catch the number between the brackets, from this SO answer)

let a = [5,5,5,5,0]
let b = [5,5,5,5,0]


const ans = prompt("Pick an element (e.g `a[2]` or `b[3]`)");

const [chosenArray, otherArray] =  ans[0] === 'a' ? [a, b] : [b, a];
const target = parseInt(ans.match(/(?<=\[).+?(?=\])/), 10);

chosenArray[target] = 1;
for (let i = target + 1; i < chosenArray.length; ++i)
  ++chosenArray[i];
for (let i = 0; i < target; ++i) 
  ++otherArray[i];


console.log(a, b)
AlexSp3
  • 2,201
  • 2
  • 7
  • 24
1

You could tkae an object with same named properties of arrays and hand over target key and index and then update until no more value is to disperse.

const
    update = (source, target, index) => {
        const keys = Object.keys(source);
        let value = source[target][index];
        source[target][index] = 0;
        while (value--) {
            source[target][index++]++;
            if (index === source[target].length) {
                index = 0;
                target = keys[(keys.indexOf(target) + 1) % keys.length];
            }
        }
        return source;
    };

console.log(update({ a: [5, 5, 5, 5, 0], b: [5, 5, 5, 5, 0] }, 'a', 2));
console.log(update({ a: [5, 5, 5, 5, 0], b: [5, 5, 5, 5, 0] }, 'b', 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392