Last active
September 30, 2015 07:51
-
-
Save mingyang91/34ae6a7b01521022d1e7 to your computer and use it in GitHub Desktop.
next函数为求str字典序的下一项,lexicographic函数为求str字典序的第n项
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
"use strict"; | |
function next (str) { | |
const charArr = str.split(''); | |
const charReverseArr = charArr.reverse(); | |
const inflectionIndex = charReverseArr.findIndex((element, index, array) => element < array[index - 1]); | |
const right = charReverseArr.slice(0, inflectionIndex); | |
const inflection = charReverseArr[inflectionIndex]; | |
const left = charReverseArr.slice(inflectionIndex + 1, charReverseArr.length); | |
// %>_<% | |
right.sort((a, b) => a > b); | |
const replaceIndex = right.findIndex(element => element > inflection); | |
const newInFlection = right.splice(replaceIndex, 1, inflection); | |
const concat = right.reverse().concat(newInFlection, left); | |
const result = concat.reverse().join(''); | |
return result; | |
} | |
/** | |
* | |
*/ | |
function lexicographic (str, nextTrick) { | |
if (nextTrick === 0) { | |
console.log(str); | |
} else { | |
lexicographic(next(str), nextTrick - 1); | |
} | |
} | |
var now = '123456789' | |
for (let i = 1; i < 2014; i++) { | |
now = next(now); | |
} | |
console.log(now); | |
// 向后推演2013次, 得到第2014个字典序 | |
lexicographic('123456789', 2013); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
next函数为求str字典序的下一项
lexicographic函数为求str字典序的第n项