|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +type C struct{ x, y int } |
| 11 | + |
| 12 | +type Config struct { |
| 13 | + A, B, P C |
| 14 | +} |
| 15 | + |
| 16 | +func parseConfigs() []Config { |
| 17 | + scanner := bufio.NewScanner(os.Stdin) |
| 18 | + |
| 19 | + configs := []Config{} |
| 20 | + config := Config{} |
| 21 | + for scanner.Scan() { |
| 22 | + line := scanner.Text() |
| 23 | + |
| 24 | + if line == "" { |
| 25 | + config = Config{} |
| 26 | + } |
| 27 | + |
| 28 | + var x, y int |
| 29 | + switch { |
| 30 | + case strings.HasPrefix(line, "Button A"): |
| 31 | + fmt.Sscanf(line, "Button A: X+%d, Y+%d", &x, &y) |
| 32 | + config.A = C{x, y} |
| 33 | + |
| 34 | + case strings.HasPrefix(line, "Button B"): |
| 35 | + fmt.Sscanf(line, "Button B: X+%d, Y+%d", &x, &y) |
| 36 | + config.B = C{x, y} |
| 37 | + |
| 38 | + case strings.HasPrefix(line, "Prize"): |
| 39 | + fmt.Sscanf(line, "Prize: X=%d, Y=%d", &x, &y) |
| 40 | + config.P = C{x, y} |
| 41 | + configs = append(configs, config) |
| 42 | + } |
| 43 | + } |
| 44 | + return configs |
| 45 | +} |
| 46 | + |
| 47 | +func solve(c Config) int { |
| 48 | + // { Px = a*Ax + b*Bx |
| 49 | + // { Py = a*Ay + b*By |
| 50 | + //------------------------- |
| 51 | + // { a = (Px - b*Bx) / Ax |
| 52 | + // { b = (Py - a*Ay) / By |
| 53 | + // |
| 54 | + // b = ( Py - ((Px-b*Bx)/Ax)*Ay ) / By |
| 55 | + // b*Ay*By = Ax*Py - Ay*Px + b*Ay*Bx |
| 56 | + // b = ( Ax*Py - Ay*Px ) / ( Ax*By - Ay*Bx ) |
| 57 | + b := (c.A.x*c.P.y - c.A.y*c.P.x) / (c.A.x*c.B.y - c.A.y*c.B.x) |
| 58 | + a := (c.P.x - b*c.B.x) / c.A.x |
| 59 | + |
| 60 | + if a*c.A.x+b*c.B.x == c.P.x && a*c.A.y+b*c.B.y == c.P.y { |
| 61 | + return 3*a + b |
| 62 | + } |
| 63 | + |
| 64 | + return 0 |
| 65 | +} |
0 commit comments