Created
June 9, 2015 02:40
-
-
Save ionox0/e7d55f2c70f84c59774c to your computer and use it in GitHub Desktop.
findCommonAncestor.js
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
// Name == ionox0 | |
process.stdin.resume(); | |
process.stdin.setEncoding("ascii"); | |
var input = ''; | |
process.stdin.on("data", function(chunk){ | |
input += chunk; | |
}); | |
process.stdin.on("end", function(){ | |
findAntecedent(input); | |
}); | |
function findAntecedent(input){ | |
input = input.trim(); | |
var lines = input.split('\n'); | |
for (var i = 1; i < lines.length - 1; i++){ | |
lines[i] = lines[i].split(','); | |
} | |
var p1 = lines[lines.length - 1].split(',')[0]; | |
var p2 = lines[lines.length - 1].split(',')[1]; | |
var p1Parents = []; | |
while (p1){ | |
p1Parents.push(p1); | |
p1 = findParent(lines, p1); | |
} | |
while (p2){ | |
if (p1Parents.indexOf(p2) != -1){ | |
console.log(p2); | |
return; | |
} | |
p2 = findParent(lines, p2); | |
} | |
} | |
function findParent(lines, child){ | |
for (var i = 1; i < lines.length - 1; i++){ | |
if (lines[i].indexOf(child) != -1 && lines[i][0] != child){ | |
return lines[i][0]; | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment