Skip to content

Instantly share code, notes, and snippets.

@NISH1001
Created March 14, 2016 07:38
Show Gist options
  • Save NISH1001/87325e49e34e310bf2b1 to your computer and use it in GitHub Desktop.
Save NISH1001/87325e49e34e310bf2b1 to your computer and use it in GitHub Desktop.
A simple combination problem that is all the possible combinations of given numbers that result in a given sum (repetition allowed)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Combination</title>
</head>
<body>
<div class="header">
<h1>Combination Problem</h1>
</div>
<div class="content">
<h3> Just enter space separated values in the input box below. :D </h3>
<form method="post"
action="#"
onsubmit="return compute();"
>
<label>Numbers : </label>
<input type="text"
id="numbers"
name="numbers"
value="1 2 3 4"
/>
<br />
<label>Sum To: </label>
<input type="number"
id="sum_to"
name="sum_to"
value="5"
/>
<br />
<input type="submit" name="submit" value="Compute" />
</form>
<h3> Result goes here </h3>
<div id="result">
</div>
</div>
<div class="footerl">
<h5>To loop is human, to recurse is divine</h5>
</div>
<script>
var result = [];
var compute = function()
{
// first clear the array
result = [];
// get form values -> space separated -> split by space
var numbers = document.getElementById("numbers").value.trim();
numbers = numbers.split(" ");
var list = [];
for(var i=0; i<numbers.length; ++i)
{
if(isNaN(numbers[i]))
{
alert("...invalid input....");
return false;
}
list.push(parseInt(numbers[i], 10));
}
var sum_to = document.getElementById("sum_to").value;
sum_to = parseInt(sum_to, 10);
func(list, [], 0, 0, sum_to);
output();
return false;
}
var func = function(numbers, res, limit, sum, sum_to)
{
if(sum == sum_to)
{
result.push(res);
return;
}
if(sum > sum_to)
{
return;
}
for(var i=0; i<numbers.length; ++i)
{
var x = numbers[i];
if(x >= limit)
{
var copy = res.slice();
copy.push(x);
func(numbers, copy, x, sum+x, sum_to);
}
}
return;
};
var output = function()
{
// now render the combinations into the div
var res_div = document.getElementById("result");
res_div.innerHTML = "";
var str = "";
for(var i=0; i<result.length; ++i)
{
str += "<br />" + result[i];
}
res_div.innerHTML = res_div.innerHTML + str;
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment