Skip to content

Instantly share code, notes, and snippets.

@matlockx
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matlockx/9fea555e31beac952dd9 to your computer and use it in GitHub Desktop.
Save matlockx/9fea555e31beac952dd9 to your computer and use it in GitHub Desktop.
<html>
<body>
<h1 id="title">Combinations</h1>
<input type="text" id="numbers" value="1,2,3,4,5" />
<input type="text" id="stars" value="1,2,3" />
<input type="submit" id="byBtn" value="Change" onclick="change()" />
<div id="info"></div>
<div id="combinations"></div>
<script>
function change() {
var numbers = document.getElementById('numbers').value.split(",");
var stars = document.getElementById('stars').value.split(",");
var c = document.getElementById('combinations');
var info = document.getElementById('info');
var myTable = "<table border='1'><tr><td>Numbers</td><td>Stars</td></tr>";
var start = performance.now();
var numberCombinations = combinations(numbers.sort(), 5);
var starCombinations = combinations(stars.sort(), 2);
for (var i = 0; i < numberCombinations.length; i++) {
for (var j = 0; j < starCombinations.length; j++) {
myTable += "<tr><td>" +numberCombinations[i] + "</td><td>" + starCombinations[j] + "</td></tr>";
}
}
info.innerHTML = "<br><br>Combinations: " + (numberCombinations.length * starCombinations.length) + "<br>" + logTime(start) + "<br><br>";
c.innerHTML = myTable + "</table>";
}
function logTime(start) {
var end = performance.now();
var time = end - start;
return 'Execution time: ' + time + ' ms';
}
function combinations(set, k) {
var i, j, combs, head, tailcombs;
if (!set || !k || k > set.length || k <= 0) {
return [];
}
if (k == set.length) {
return [set];
}
if (k == 1) {
combs = [];
for (i = 0; i < set.length; i++) {
combs.push([set[i]]);
}
return combs;
}
combs = [];
for (i = 0; i < set.length - k + 1; i++) {
head = set.slice(i, i + 1);
tailcombs = combinations(set.slice(i + 1), k - 1);
for (j = 0; j < tailcombs.length; j++) {
combs.push(head.concat(tailcombs[j]));
}
}
return combs;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment