1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00

go: add «399. Evaluate Division»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-26 00:10:14 +02:00
parent 4164be15ac
commit 955f89bae0
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

75
go/evaluate-division.go Normal file
View file

@ -0,0 +1,75 @@
package main
type Expression struct {
variable string
constant float64
}
func calcEquation(equations [][]string, values []float64, queries [][]string) []float64 {
process := func() map[string]([]Expression) {
g := make(map[string]([]Expression), 0)
for i, eq := range equations {
x, y := eq[0], eq[1]
if g[x] == nil {
g[x] = make([]Expression, 0)
}
g[x] = append(g[x], Expression{
variable: y,
constant: values[i],
})
if g[y] == nil {
g[y] = make([]Expression, 0)
}
g[y] = append(g[y], Expression{
variable: x,
constant: 1 / values[i],
})
}
return g
}
graph := process()
var dfs func(map[string]bool, string, string, float64, *float64)
dfs = func(visited map[string]bool, src, dest string, product float64, result *float64) {
if visited[src] {
return
}
visited[src] = true
if src == dest {
*result = product
return
}
neighbors, hasNeighbors := graph[src]
if !hasNeighbors {
return
}
for _, nextSrc := range neighbors {
dfs(visited, nextSrc.variable, dest, product*nextSrc.constant, result)
}
}
getResult := func(src, dst string) float64 {
result := -1.0
visited := make(map[string]bool, 0)
if graph[src] != nil {
dfs(visited, src, dst, 1.0, &result)
}
return result
}
results := make([]float64, len(queries))
for i, query := range queries {
results[i] = getResult(query[0], query[1])
}
return results
}