Last active
August 29, 2015 14:13
-
-
Save bmvakili/521d36b8825190453a8d to your computer and use it in GitHub Desktop.
Set with intersection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Set intersect | |
* The algorithm is provided by Ophir LOJKINE. I modified it to work for sets. | |
* @author Ophir LOJKINE | |
* https://gist.github.com/lovasoa/3361645 | |
* @author Bijan Vakili | |
*/ | |
Set.prototype.intersect = function() { | |
var i, all, shortest, nShortest, n, len, ret = [], obj={}, nOthers; | |
arguments[arguments.length++] = this; | |
nOthers = arguments.length-1; | |
nShortest = arguments[0].size; | |
shortest = 0; | |
for (i=0; i<=nOthers; i++){ | |
n = arguments[i].size; | |
console.log("n: " + n); | |
if (n<nShortest) { | |
shortest = i; | |
nShortest = n; | |
} | |
} | |
for (i=0; i<=nOthers; i++) { | |
n = (i===shortest)?0:(i||shortest); //Read the shortest array first. Read the first array instead of the shortest | |
len = arguments[n].size; | |
console.log("len " + len); | |
arr = Array.from(arguments[n]); | |
for (var j=0; j<len; j++) { | |
var elem = arr[j]; | |
if(obj[elem] === i-1) { | |
if(i === nOthers) { | |
ret.push(elem); | |
obj[elem]=0; | |
} else { | |
obj[elem]=i; | |
} | |
} else if (i===0) { | |
obj[elem]=0; | |
} | |
} | |
} | |
return ret; | |
}; | |
/** Begin Test **/ | |
$(document).ready(function () { | |
function logIt(x) { | |
$("#result-question3").append(x + "<br />"); | |
console.log(x); | |
} | |
var x = new Set(); | |
x.add("1"); | |
x.add("2"); | |
x.add("3"); | |
x.add("7"); | |
var y = new Set(); | |
y.add("1"); | |
y.add("5"); | |
y.add("7"); | |
var z = new Set(); | |
z.add("1"); | |
z.add("2"); | |
z.add("3"); | |
z.add("7"); | |
logIt("Set x : " + JSON.stringify(Array.from(x))); | |
logIt("Set y : " + JSON.stringify(Array.from(y))); | |
logIt("Set z : " + JSON.stringify(Array.from(z))); | |
result = x.intersect(y, z); | |
logIt("Intersection: " + JSON.stringify(result)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment