Created
June 9, 2021 03:16
-
-
Save CarlaTeo/9bca7acee5e53884bb4cc0b4258da339 to your computer and use it in GitHub Desktop.
[JS] Minimize permutations
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
function getPermutations(arr, minOp, original = []) { | |
const result = []; | |
for(let size = 2; size <= arr.length; size++) { | |
for(let i = 0; i + size <= arr.length; i ++) { | |
const permutation = [ | |
...arr.slice(0, i), | |
...arr.slice(i, i + size).reverse(), | |
...arr.slice(i + size) | |
]; | |
if(!isEqual(original, permutation)) { | |
result.push({ | |
permutation, | |
minOp, | |
original: arr, | |
}); | |
} | |
} | |
} | |
return result; | |
} | |
function isEqual(arr1, arr2) { | |
if(arr1.length !== arr2.length) return false; | |
for(const [idx, val] of arr1.entries()) { | |
if(val !== arr2[idx]) return false; | |
} | |
return true; | |
} | |
function minOperations(arr) { | |
let minOp = 1; | |
const sortedArr = [...arr].sort((a, b) => a > b ? 1 : -1); | |
const queue = getPermutations(arr, minOp); | |
while(queue.length) { | |
const {permutation, minOp, original} = queue.shift(); | |
if(isEqual(permutation, sortedArr)) return minOp; | |
queue.push(...getPermutations(permutation, minOp + 1, original)); | |
} | |
throw "Invalid input: " + arr.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment