Last active
February 27, 2024 10:49
-
-
Save marsgpl/5e6e5c323ae8f766f1d1f3a064b60473 to your computer and use it in GitHub Desktop.
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
const FACTS = [ | |
'm = 3.28 ft', | |
'ft = 12 in', | |
'hr = 60 min', | |
'min = 60 sec', | |
] | |
const QUERY = '2 m = ? in' | |
const CORRECT_ANSWER = 78.72 | |
// implement function answerQuery(query: string, facts: string[]): number | |
// i.e. find '?' value | |
// example solution | |
type Dict = Map<string, [string, number]> | |
function parseStatement(statement: string) { | |
const [xa, yb] = statement.split(/\s*=\s*/) | |
let [x, a] = xa.split(/\s+/) | |
let [y, b] = yb.split(/\s+/) | |
if (!a) { | |
a = x | |
x = '1' | |
} | |
if (!b) { | |
b = y | |
y = '1' | |
} | |
return { | |
x: Number(x), | |
a, | |
y: Number(y), | |
b, | |
} | |
} | |
// m = 3.28 ft | |
function parseFacts(facts: string[]) { | |
const dict: Dict = new Map() | |
facts.forEach(fact => { | |
const { x, a, y, b } = parseStatement(fact) | |
dict.set(a, [b, y / x]) | |
}) | |
return dict | |
} | |
// 2 m = ? in | |
function answerQuery(query: string, facts: string[]): number { | |
const dict = parseFacts(facts) | |
const { x, a, y, b } = parseStatement(query) | |
// let's assume y should always be '?' | |
if (!Number.isNaN(y)) { | |
throw Error('Unsupported query format') | |
} | |
let finalRatio = 1 | |
let finalUnit = a | |
while (finalUnit !== b) { | |
const [unit, ratio] = dict.get(finalUnit) || [] | |
if (!unit) { | |
throw Error('Not enough facts') | |
} | |
finalRatio *= (ratio || 1) | |
finalUnit = unit | |
} | |
return x * finalRatio | |
} | |
const answer = answerQuery(QUERY, FACTS) | |
console.log(answer === CORRECT_ANSWER ? 'ok' : 'fail') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment