Skip to content

Instantly share code, notes, and snippets.

@zhangchiqing
Created April 2, 2017 18:33
Show Gist options
  • Save zhangchiqing/acda542fa58bda2de3a58503db6308d5 to your computer and use it in GitHub Desktop.
Save zhangchiqing/acda542fa58bda2de3a58503db6308d5 to your computer and use it in GitHub Desktop.
PremutationsN
// [a] -> [[a]] -> [[a]]
var iter = function(arr, parents) {
if (R.isEmpty(arr)) {
return parents;
}
return R.addIndex(R.chain)(function(a, index) {
return iter(
R.remove(index, 1, arr),
R.map(R.append(a), parents));
}, arr);
};
// [a] -> [[a]]
var premutations = function(arr) {
return iter(arr, [[]]);
};
// Number -> [[Number]]
var premutationsN = function(n) {
return premutations(R.range(0, n));
};
premutationsN(3);
// [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment