|
| 1 | +// Copyright (c) Miloš Rackov 2022 |
| 2 | +// Distributed under the Boost Software License, Version 1.0. |
| 3 | +// (See accompanying file LICENSE or copy at |
| 4 | +// https://www.boost.org/LICENSE_1_0.txt) |
| 5 | + |
| 6 | +package part2 |
| 7 | + |
| 8 | +import ( |
| 9 | + "sort" |
| 10 | + "strconv" |
| 11 | + "strings" |
| 12 | +) |
| 13 | + |
| 14 | +var monkeys = map[string]string{} |
| 15 | + |
| 16 | +func Part2(input string) int { |
| 17 | + for _, s := range strings.Split(input, "\n") { |
| 18 | + s := strings.Split(s, ": ") |
| 19 | + monkeys[s[0]] = s[1] |
| 20 | + } |
| 21 | + |
| 22 | + monkeys["humn"] = "0" |
| 23 | + s := strings.Fields(monkeys["root"]) |
| 24 | + if solve(s[0]) < solve(s[2]) { |
| 25 | + s[0], s[2] = s[2], s[0] |
| 26 | + } |
| 27 | + |
| 28 | + i, _ := sort.Find(1e16, func(v int) int { |
| 29 | + monkeys["humn"] = strconv.Itoa(v) |
| 30 | + return solve(s[0]) - solve(s[2]) |
| 31 | + }) |
| 32 | + return i |
| 33 | +} |
| 34 | + |
| 35 | +func solve(expr string) int { |
| 36 | + if v, err := strconv.Atoi(monkeys[expr]); err == nil { |
| 37 | + return v |
| 38 | + } |
| 39 | + |
| 40 | + s := strings.Fields(monkeys[expr]) |
| 41 | + return map[string]func(int, int) int{ |
| 42 | + "+": func(a, b int) int { return a + b }, |
| 43 | + "-": func(a, b int) int { return a - b }, |
| 44 | + "*": func(a, b int) int { return a * b }, |
| 45 | + "/": func(a, b int) int { return a / b }, |
| 46 | + }[s[1]](solve(s[0]), solve(s[2])) |
| 47 | +} |
0 commit comments