Skip to content

Instantly share code, notes, and snippets.

@BiosBoy
Created March 15, 2024 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BiosBoy/ce0f784ff6fe4cce8f16c275d0cb800f to your computer and use it in GitHub Desktop.
Save BiosBoy/ce0f784ff6fe4cce8f16c275d0cb800f to your computer and use it in GitHub Desktop.
const input1 = [1, 2, 5, 3, 4, 7, 8, 6];
const input2 = [2, 5, 1, 3, 4];
const chaos = (arr) => {
let operationCount = 0;
let isChaos = false;
arr.forEach((_, idx) => {
const nextReversedIdx = arr.length - idx;
const currentReversedIndex = nextReversedIdx - 1;
const currentValue = arr[currentReversedIndex];
const nextValue = arr[nextReversedIdx];
if (currentValue > nextValue) {
const tempArr = arr.slice(nextReversedIdx, arr.length);
tempArr.forEach((__, innerIdx) => {
if (
currentValue > tempArr[innerIdx] &&
currentValue > tempArr[innerIdx + 1] &&
currentValue > tempArr[innerIdx + 2]
) {
!isChaos && console.log("Too chaotic");
isChaos = true;
}
if (currentValue > tempArr[innerIdx]) {
operationCount++;
const value = arr.splice(currentReversedIndex + innerIdx, 1);
arr.splice(nextReversedIdx + innerIdx, 0, ...value);
}
});
}
});
!isChaos && console.log(operationCount);
};
chaos(input1);
chaos(input2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment