RosettaCodeData/Task/Permutations/Lambdatalk/permutations-2.lambdatalk
2023-07-01 13:44:08 -04:00

69 lines
1.3 KiB
Text

1) permutations on sentences
{script
var S_perm = function(a) {
if (a.length < 2) return [a];
var b = [];
for (var c = 0; c < a.length; c++) {
var e = a.splice(c, 1), f = S_perm(a);
for (var d = 0; d < f.length; d++)
b.push( e.concat( f[d]) );
a.splice(c, 0, e[0])
}
return b
}
LAMBDATALK.DICT['S.perm'] = function() { // {S.perm 1 2 3}
return S_perm( arguments[0].trim()
.split(" ") )
.join(" ")
.replace(/\s/g,"{br}")
};
}
{S.perm 1 2 3}
->
1,2,3
1,3,2
2,1,3
2,3,1
3,1,2
3,2,1
{S.perm hello brave world}
->
hello,brave,world
hello,world,brave
brave,hello,world
brave,world,hello
world,hello,brave
world,brave,hello
2) permutations on words
{script
var W_perm = function(word) {
if (word.length === 1) return [word]
var results = [];
for (var i = 0; i < word.length; i++) {
var buti = W_perm( word.substring(0, i) + word.substring(i + 1) );
for (var j = 0; j < buti.length; j++)
results.push(word[i] + buti[j]);
}
return results;
};
LAMBDATALK.DICT['W.perm'] = function() { // {W.perm 123}
return W_perm( arguments[0].trim() ).join("{br}")
};
}
{W.perm 123}
->
123
132
213
231
312
321