-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcombinations.html
42 lines (39 loc) · 1.72 KB
/
combinations.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<script type="text/javascript">
function getCombos(chars, k, indent) {
if (indent === undefined) {
indent = 0;
}
let debugMsg = ".".repeat(indent) + "In getCombos('" + chars + "', " + k + ")";
document.write(debugMsg + ", start.<br />");
if (k == 0) {
// BASE CASE
document.write(debugMsg + " base case returns ['']<br />");
// If k asks for 0-combinations, return '' as the selection of
// zero letters from chars.
return [""];
} else if (chars == "") {
// BASE CASE
document.write(debugMsg + " base case returns []<br />");
return []; // A blank chars has no combinations, no matter what k is.
}
// RECURSIVE CASE
let combinations = [];
// First part, get the combos that include the head:
let head = chars.slice(0, 1);
let tail = chars.slice(1, chars.length);
document.write(debugMsg + " part 1, get combos with head '" + head + "'<br />");
let tailCombos = getCombos(tail, k - 1, indent + 1);
document.write(".".repeat(indent) + "Adding head '" + head + "' to tail combos:<br />");
for (tailCombo of tailCombos) {
document.write(".".repeat(indent) + "New combination " + head + tailCombo + "<br />");
combinations.push(head + tailCombo);
}
// Second part, get the combos that don't include the head:
document.write(debugMsg + " part 2, get combos without head '" + head + "')<br />");
combinations = combinations.concat(getCombos(tail, k, indent + 1));
document.write(debugMsg + " results are " + combinations + "<br />");
return combinations;
}
document.write('<pre>2-combinations of "ABC":<br />');
document.write("Results: " + getCombos("ABC", 2) + "<br /></pre>");
</script>