Our Permutation code in Javascript.
Permutation JavaScript File:
var local_store = {};
var perm_store = {};
var index;
// till the ground for shuffle to grind on
function possibleWordPermutations(candidates, size) {
var combination = possibleWordCombinations(candidates, size);
// illegal 'r' value
if (combination[0] === undefined || r == 1) {
perm_store = combination;
} else {
var i, n = 0;
for (i in combination) {
index = r - 1;
local_store = {0: [], 1: []};
// copy up last two elements of 'comb_store[i]'
local_store[0][0] = local_store[1][1] = comb_store[i][index--];
local_store[0][1] = local_store[1][0] = comb_store[i][index--];
if (r > 2) {
shuffleWord(local_store, i);
}
var m;
for (m in local_store) {
perm_store[n++] = local_store[m];
}
}
}
return perm_store;
}
function shuffleWord(arg_store, i) {
local_store = {};
var j, k = 0;
for (j in arg_store) {
var members = arg_store[j];
// add last 'origin' element to this list of members
members.push(comb_store[i][index]);
var shift_index = members.length;
var temp_char;
// shuffle this pack of words
while (shift_index > 0) {
var find = false, m;
// skip if already in store
for (m in local_store) {
if (JSON.stringify(local_store[m]) == JSON.stringify(members)) {
find = true;
break;
}
}
if (!find) {
local_store[k++] = members.slice(0);
}
// interchange these two neighbours
if (--shift_index > 0 && members[shift_index] != members[shift_index - 1]) {
temp_char = members[shift_index];
members[shift_index] = members[shift_index - 1];
members[shift_index - 1] = temp_char;
}
}
}
// Are there any elements left? repeat if yes
if (index-- > 0) {
shuffleWord(local_store, i);
}
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Permutation</title>
<script src="Combination.js"></script>
<script src="Permutation.js"></script>
</head>
<body>
<h3>Possible Word/Letter/Object Arrangements</h3>
<!-- This is where the result will be displayed when it is ready.-->
<div id="word_perm"></div>
<script>
var result =
possibleWordPermutations(["Eno", "Chidi", "Olu", "Ahmed", "Osas", "Gbeda"], 3);
var print = "", set, count = 0;
for (set in result) {
print += ++count + ": [" + result[set].join(", ") + "]<br/>";
}
document.getElementById("word_perm").innerHTML +=
words.join(", ") + " permutation " + r + ":<br/><br/>" + print +
"<br/><br/>Number of ways is " + count + ".";
</script>
</body>
</html>
Try it out!
Elegance (0.0)