I am writing a function that analyzes an array, but that higher function is not the problem. I tried console.log on my newly initialized array of five 0s (tried 3 ways) and I get a log of a different array. What is going on?
function minimumBribes(q) {
var totalBribes = 0;
var tooChaotic = false;
var n = q.length;
var bribesPerPerson = new Array(n).fill(0, 0, n);
//var bribesPerPerson = new Array(n).fill(0);
//var bribesPerPerson = [0, 0, 0, 0, 0];
console.log(bribesPerPerson);
for (var i = n - 1; i > -1; i--) {
var newI = i + bribesPerPerson[i];
if (i + 1 === q[newI]) {
//console.log(newI);
//console.log(i + 1 === q[newI]);
} else if (i + 1 === q[newI - 1]) {
bribesPerPerson[i]++;
totalBribes++;
} else if (i + 1 === q[newI - 2]) {
bribesPerPerson[i]++;
bribesPerPerson[i - 1]++;
totalBribes = totalBribes + 2;
} else {
tooChaotic = true;
}
}
//var q = [1, 2, 5, 3, 4, 7, 8, 6];
//runningTotal =
//[0 0 0 0 0 0 0 0]
if (tooChaotic === true) {
console.log("Too chaotic");
} else {
console.log(totalBribes);
}
}
//var q = [2, 1, 3, 4, 5];
var q = [2, 1, 5, 3, 4];
//var q = [2, 5, 1, 3, 4];
//var q = [1, 2, 5, 3, 4, 7, 8, 6];
minimumBribes(q);
Stdout: [0, 1, 0, 1, 1] Stdout: Too chaotic