Our Combination code in Javascript.
Combination JavaScript File:
var words, r; // min length of word
var comb_store = {}, c_index = 0;
var i;
// point of entry
function possibleWordCombinations(candidates, size) {
words = candidates;
r = size;
i = 0;
// check for conformity
if (r <= 0 || r > words.length) {
comb_store = {};
} else if (r == 1) {
for (; i < words.length; i++) {
comb_store[c_index] = [];
comb_store[c_index++].push(words[i]);
}
} else {
progressiveCombination();
}
return comb_store;
}
// do combinations for all 'words' element
function progressiveCombination() {
repetitivePairing([words[i]], i + 1);
if (i + r <= words.length) {
// move on to next degree
i++;
progressiveCombination();
}
}
// do all possible combinations for 1st element of this array
function repetitivePairing(prefix, position) {
var auxiliary_store = {};
for (var j = 0; position < words.length; position++, j++) {
// check if desired -- r -- size will be realised
if (r - prefix.length <= words.length - position) {
auxiliary_store[j] = prefix.slice(0);
auxiliary_store[j].push(words[position]);
if (auxiliary_store[j].length < r) {
// see to adding next word on
repetitivePairing(auxiliary_store[j], position + 1);
} else {
comb_store[c_index++] = auxiliary_store[j];
}
}
}
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Word Combination</title>
<script src="Combination.js"></script>
</head>
<body>
<h3>Selection Without Repetition</h3>
<!-- This is where the result will be displayed when it is ready.-->
<div id="word_combo"></div>
<script>
var result =
possibleWordCombinations(["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_combo").innerHTML +=
words.join(", ") + " combination " + r + ":<br/><br/>" + print +
"<br/><br/>Number of ways is " + count + ".";
</script>
</body>
</html>
Try it out!
Elegance (0.0)