Last active
July 7, 2017 22:00
-
-
Save waieez/8b40992fd904f165dcc399bd981d9432 to your computer and use it in GitHub Desktop.
HackerRank Join Question
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
var left = [ | |
"apple", | |
"grape", | |
"grape", | |
"melon" | |
] | |
var right = [ | |
"grape", | |
"lemon", | |
"apple" | |
] | |
match('left', left, right) | |
/* | |
* Complete the function below. | |
*/ | |
function match(matchtype, left, right) { | |
//console.log(matchtype, left, right) | |
if (matchtype == 'left') { | |
return leftjoin(left, right) | |
} else if (matchtype == 'right') { | |
return rightjoin(left, right) | |
} else if (matchtype == 'inner') { | |
return innerjoin(left, right) | |
} | |
} | |
function leftjoin(A, B) { | |
//idx of left + match in right or no match | |
var h = hash(B) | |
var rows = [] | |
for(var i = 0; i < A.length; i++) { | |
var r = h[A[i]] | |
if (r === undefined) { | |
r = [] | |
} | |
for (var j = 0; j < r.length; j++) { | |
rows.push([i, r[j]]) | |
console.log(i, r[j]) | |
} | |
if (r.length == 0) { | |
rows.push([i, -1]) | |
console.log(i, -1) | |
} | |
} | |
return rows | |
} | |
function rightjoin(A, B) { | |
//idx of left + match in right or no match | |
var h = hash(A) | |
var rows = [] | |
for(var i = 0; i < B.length; i++) { | |
var r = h[B[i]] | |
if (r === undefined) { | |
r = [] | |
} | |
for (var j = 0; j < r.length; j++) { | |
rows.push([r[j], i]) | |
console.log(r[j], i) | |
} | |
if (r.length == 0) { | |
rows.push([-1, i]) | |
console.log(-1, i) | |
} | |
} | |
return rows | |
} | |
function innerjoin(A, B) { | |
var h = hash(B) | |
var rows = [] | |
for(var i = 0; i < A.length; i++) { | |
var r = h[A[i]] | |
if (r) { | |
for (var j = 0; j < r.length; j++) { | |
rows.push([i,r[j]]) | |
console.log(i, r[j]) | |
} | |
} | |
} | |
return rows | |
} | |
function hash(A) { | |
var h = {} | |
for (var i = 0; i < A.length; i++) { | |
if (!h[A[i]]) { | |
h[A[i]] = [] | |
} | |
h[A[i]].push(i) | |
} | |
return h | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment