Created
February 27, 2020 00:57
-
-
Save RP-3/050e8147f9a0a120087b4d4fa3298059 to your computer and use it in GitHub Desktop.
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
/** | |
* @param {string[][]} equations | |
* @param {number[]} values | |
* @param {string[][]} queries | |
* @return {number[]} | |
*/ | |
var calcEquation = function(equations, values, queries) { | |
const idents = {}; // could use map but longer syntax | |
equations.forEach((eq, i) => { | |
const [numerator, denominator] = eq; | |
idents[numerator] = idents[numerator] || []; | |
idents[denominator] = idents[denominator] || []; | |
idents[numerator].push([denominator, values[i], '*']); | |
idents[denominator].push([numerator, values[i], '/']); | |
}); | |
return queries.map(([n, d]) => { | |
if(n === d && idents[n]) return 1; | |
return find(n, d) || -1; | |
}); | |
function find(n, d){ // finds n in terms of d. Returns number | null | |
const seen = new Set(); | |
const traverse = (n, d) => { | |
if(seen.has(`${n}:${d}`)) return null; | |
else seen.add(`${n}:${d}`); | |
if(idents[n]){ | |
for(let i=0; i< idents[n].length; i++){ | |
const [variable, constant, operator] = idents[n][i]; | |
if(variable === d) return operator === '*' ? constant : (1/constant); | |
const val = traverse(variable, d); | |
if(val !== null) return operator === '*' ? constant * val : val / constant; | |
} | |
} | |
return null; | |
}; | |
return traverse(n, d); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment