JSFiddle - React, Tailwind, and code Playground
by ifandelse
HTML
<div id="results"></div>
JavaScript
var list = [0,1,2,3,4,5,6,7,8,9],
sum = 12;
var f1 = function(ls, x) {
var i = 0, j;
for(; i < ls.length - 1; i++) {
for(j = 0; j <= ls.length - 1; j++) {
if(i !== j && ls[i] + ls[j] === x) {
return true;
}
}
}
return false;
};
var f2 = function(ls,x) {
console.log("SUM: " + x);
var i = 0, j;
for(; i <= ls.length-1; i++) {
j = i + 1;
for(; j <= ls.length -1; j++) {
console.log(" ls[" + i + "] + ls[" + j + "] --> " + ls[i] + " + " + ls[j]);
if(ls[j] + ls[i] === x) {
console.log(" BAM!");
return true;
}
}
}
return false;
};
var f3 = function(ls, l) {
var cache = {}, curVal, diff;
for(var i = 0; i <= ls.length; i++) {
curVal = ls[i];
if(!cache[curVal]) {
diff = l - curVal;
cache[curVal] = diff;
if(cache[diff]) {
return true;
}
}
}
return false;
}
//$("<p>f1(" + JSON.stringify(list) + ", " + sum + "): " + f1(list, sum) + "</p>").appendTo("#results");
//$("<p>f2(" + JSON.stringify(list) + ", " + sum + "): " + f2(list, sum) + "</p>").appendTo("#results");
var a, b, c = {};
for(a = 0; a <= list.length - 1; a++ ) {
b = a;
for(; b <= list.length - 1; b++) {
var thisSum = list[a] + list[b];
if(!c[thisSum]) {
$("<p>f2(" + JSON.stringify(list) + ", " + thisSum + "): " + f3(list, thisSum) + "</p>").appendTo("#results");
c[thisSum] = true;
}
}
}