Created
July 1, 2023 14:10
-
-
Save SamuelNittala/dd02b6ee11ea3bb0dd20f963263adbb8 to your computer and use it in GitHub Desktop.
jane-street: answer facts problem (https://www.youtube.com/watch?v=V8DGdPkBBxg)
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'], | |
['m', 100, 'cm'], | |
['ft', 12, 'in'], | |
['hr', 60, 'min'], | |
['min', 60, 'sec'], | |
]; | |
const construct_graph = (facts) => { | |
const graph = {}; | |
for (let i = 0; i < facts.length; ++i) { | |
const n = facts[i][0]; | |
const m = facts[i][2]; | |
const val = facts[i][1]; | |
if (graph[n]) { | |
graph[n].push([m, val]); | |
} else { | |
graph[n] = [[m, val]]; | |
} | |
if (graph[m]) { | |
graph[m].push([n, 1 / val]); | |
} else { | |
graph[m] = [[n, 1 / val]]; | |
} | |
} | |
return graph; | |
}; | |
function dfs(graph, start, end, visited, path) { | |
visited[start] = true; | |
for (let i = 0; i < graph[start].length; ++i) { | |
const curr_node = graph[start][i][0]; | |
const unit_val = graph[start][i][1]; | |
if (!visited[curr_node]) { | |
path.push([curr_node, unit_val]); | |
dfs(graph, curr_node, end, visited, path, start); | |
} | |
} | |
} | |
const calc_query = (val, from, to) => { | |
const graph = construct_graph(facts); | |
const p = [[from, 1]]; | |
dfs(graph, from, to, {}, p); | |
let res = val; | |
console.log(p); | |
let invalid = true; | |
for (let i = 0; i < p.length; i++) { | |
const [name, val] = p[i]; | |
res *= val; | |
if (name == to) { | |
invalid = false; | |
break; | |
} | |
} | |
return invalid ? 'invalid conversion' : res; | |
}; | |
const rs = calc_query(30, 'min', 'hr'); | |
console.log(rs); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment