Created
October 13, 2011 08:39
-
-
Save anjanesh/1283755 to your computer and use it in GitHub Desktop.
Find Intersection Among Arrays
This file contains 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
/* | |
ar : can be an array of arrays or an asssociative array | |
Examples: | |
================ | |
intersect([[76,80,11,31,34,82,100], [13,31,66,43,73,100,73,10]]) | |
will give [31,100] | |
intersect( | |
{ | |
colors1 : ['black', 'orange', 'white', 'blue', 'yellow'], | |
colors2 : ['green', 'yellow', 'red', 'brown', 'black'] | |
}) | |
will give ['black', 'yellow'] | |
intersect( | |
{ | |
colors1 : ['black', 'orange', 'white', 'blue', 'yellow'], | |
colors2 : ['green', 'yellow', 'red', 'brown', 'black'], | |
colors3 : ['yellow', 'red', 'pink', 'orange'] | |
}) | |
will give ['yellow'] | |
*/ | |
function intersect(ar) | |
{ | |
if (ar == null) return false; | |
var a = new Array(); | |
if (ar.length == undefined) // Associative Array | |
{ | |
for (var i in ar) | |
a.push(ar[i]); | |
} | |
else | |
a = ar; | |
if (a.length == 1) return false; // Single array ? Nothing to intersect with | |
var common = new Array(); | |
function loop(a, index, s_index, e_index) | |
{ | |
if (index == null) index = 0; | |
if (s_index == null) s_index = 0; | |
if (e_index == null) e_index = a[index].length; | |
if (index == a.length - 1) return; | |
for (var i = s_index; i < e_index; i++) | |
{ | |
if (common.indexOf(a[index][i]) != -1) continue; | |
for (var j = 0; j < a[index + 1].length; j++) | |
{ | |
if (a[index][i] != a[index+1][j]) continue; | |
loop(a, index + 1, j, j + 1); | |
if (index + 1 == a.length - 1) { common.push(a[index][i]); break; } | |
} | |
} | |
} | |
loop(a); | |
return common; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment