New Year Chaos
newYears([2, 1, 5, 3, 4]);
newYears([1, 2, 5, 3, 7, 8, 6, 4]);function minimumBribes(arr: number[]) {
const TOO_CHAOTIC = "Too Chaotic";
let total = 0;
for (let currentPos = 0; currentPos < arr.length; currentPos++) {
// getting original position using - indexing (starts at 0)
const originalPos = arr[currentPos] - 1;
// diff = how far person has moved
const diff = originalPos - currentPos;
if (diff > 2) return console.log(TOO_CHAOTIC);
console.log(currentPos, arr[currentPos], originalPos, diff);
// We have a negative integer, because we're looking
// behind us for if we have been bribed
if (diff <= 0) {
// check each person starting from one person ahead of originalPo
// up until currentPos
for (let j = Math.max(0, originalPos - 1); j < currentPos; j++) {
const startOfForwardPerson = arr[j] - 1;
// If a person in front of current person started BEHIND
// current person, then current person MUST have been bribed by
if (startOfForwardPerson > originalPos) {
total++;
}
}
}
}
return total;
}Notes
function newYears(arr: number[]) { let counter = 0; let chaos = 0; for (let i = 0; i < arr.length; i++) { if (arr[i] !== i + 1) { if (arr[i] === i + 2 || arr[i] === i + 3) { const temp = arr[i + 1]; arr[i + 1] = arr[i]; arr[i] = temp; counter++; } else { chaos++; } } } return chaos > counter ? "Too Chaotic" : counter; }
Last updated