Possible Selections With Repetition.
Imagine being given the opportunity to pick six (6) exercise books
from a book-shop having 10 different brands of exercise books -
Ben 10, Chelsea F.C., Superman, Tottenham F.C.,
Indomitables, Manchester City F.C., Spider Man,
Power Rangers, Liverpool F.C. and Bat Man exercise books.
If you happen to be a big Power Rangers fan, nothing stops you from
selecting all 6 exercise books to be Power Rangers exercise books.
But you can as well decide to pick only 3 Power Rangers exercise books
and make up for the other 3 with any other brands of exercise book.
Code for Repetitive Selection in JavaScript
The algorithm for Selection with Repetition will be a lot similar
to that of combination.
-
Beginning with the first member in the mother set, match it separately with
every member - including itself - until the required Selection group-size (r)
is reached.
-
When every possible Selection with this member is exhausted,
move to the next member in the mother set and repeat Step I.
This is how our Repetitive Selection code in JavaScript will work.
Create 2 new files; On Notepad++: File, New.
Call them Selection.html
and Selection.js
respectively.
Type out the adjoining JavaScript code for Selection with Repetition.
Selection with Repetition - .html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Selection</title>
<script src="Selection.js"></script>
</head>
<body>
<h3>Possible Selections with Repetition</h3>
<div id="word_select"></div>
<script>
var result =
groupSelection([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3);
var print = "", set, count = 0;
for (set in result) {
print += ++count + ": [" + result[set].join(", ") + "]<br/>";
}
document.getElementById("word_select").innerHTML +=
words.join(", ") + " selection " + r + ":<br/><br/>" + print +
"<br/><br/>Number of ways is " + count + ".";
</script>
</body>
</html>
JavaScript code for Selection with Repetition - .js
var words;
var r;
var i;
var complete_group = {}, c_index = 0;
function groupSelection(candidates, size) {
words = candidates;
r = size;
i = 0;
recursiveFillUp([]);
return complete_group;
}
function recursiveFillUp(temp) {
var picked_elements = [];
var j = i;
while (j < words.length) {
picked_elements[j] = temp.slice(0);
picked_elements[j].push(words[j]);
if (i >= words.length) {
i = j;
}
if (picked_elements[j].length == r) {
complete_group[c_index++] = picked_elements[j];
} else if (picked_elements[j].length < r) {
recursiveFillUp(picked_elements[j]);
}
j++;
}
if (picked_elements[--j] !== undefined && picked_elements[j].length == r) {
i++;
}
}