Skip to content

Instantly share code, notes, and snippets.

@mingyang91
Last active September 30, 2015 07:51
Show Gist options
  • Save mingyang91/34ae6a7b01521022d1e7 to your computer and use it in GitHub Desktop.
Save mingyang91/34ae6a7b01521022d1e7 to your computer and use it in GitHub Desktop.
next函数为求str字典序的下一项,lexicographic函数为求str字典序的第n项
"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);
@mingyang91
Copy link
Author

next函数为求str字典序的下一项
lexicographic函数为求str字典序的第n项

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment