Created
March 15, 2024 12:21
-
-
Save BiosBoy/ce0f784ff6fe4cce8f16c275d0cb800f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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