Created
January 17, 2020 19:56
-
-
Save MaxGraey/6719489a030eb0e8dcd9699181563dd9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 isOrdered = arr => !arr.some((v, i) => v == arr[i + 1]); | |
function swap(alphabets, idx1, idx2) { | |
var t = alphabets[idx1]; | |
alphabets[idx1] = alphabets[idx2]; | |
alphabets[idx2] = t; | |
return alphabets; | |
} | |
function permute(alphabets, startIndex = 0, endIndex = alphabets.length - 1) { | |
if (startIndex !== endIndex) { | |
for (var i = startIndex; i <= endIndex; i++) { | |
if (isOrdered(alphabets)) return true; | |
swap(alphabets, startIndex, i); | |
if (permute(alphabets, startIndex + 1, endIndex)) { | |
return true; | |
} | |
swap(alphabets, i, startIndex); | |
} | |
} | |
return false; | |
} | |
function reorder(str) { | |
const arr = str.split('').map(c => c.codePointAt(0)); | |
if (permute(arr)) { | |
return arr.map(c => String.fromCodePoint(c)).join(''); | |
} | |
return null; | |
} | |
console.log(reorder('аабсд')); // абасд | |
console.log(reorder('ааабс')); // асаба | |
console.log(reorder('аааас')); // null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment