123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- package main
- import (
- "bufio"
- "errors"
- "fmt"
- "io"
- "log"
- "os"
- "strconv"
- "strings"
- )
- type Coord struct {
- x, y int
- }
- type Robots struct {
- P []Coord
- V []Coord
- }
- func main() {
- robots := Robots{
- P: make([]Coord, 0, 16),
- V: make([]Coord, 0, 16),
- }
- r := bufio.NewReader(os.Stdin)
- // Read input
- i := 0
- for {
- i++
- line, err := r.ReadString('\n')
- if errors.Is(err, io.EOF) {
- break
- }
- if err != nil {
- log.Fatalf("While reading input: %v", err)
- }
- if len(line) > 0 {
- line = line[:len(line)-1]
- }
- fs := strings.Fields(line)
- if len(fs) != 2 {
- log.Fatalf("Unexpected number of fields in line: %#v", line)
- }
- // Position
- parts := strings.Split(fs[0], "=")
- parts = strings.Split(parts[1], ",")
- x, err := strconv.ParseInt(parts[0], 10, 32)
- if err != nil {
- log.Fatalf("While parsing x coordinate of position at line %d: %q", i, line)
- }
- y, err := strconv.ParseInt(parts[1], 10, 32)
- if err != nil {
- log.Fatalf("While parsing y coordinate of position at line %d: %q", i, line)
- }
- robots.P = append(robots.P, Coord{int(x), int(y)})
- // Velocity
- parts = strings.Split(fs[1], "=")
- parts = strings.Split(parts[1], ",")
- x, err = strconv.ParseInt(parts[0], 10, 32)
- if err != nil {
- log.Fatalf("While parsing x component of velocity at line %d: %q", i, line)
- }
- y, err = strconv.ParseInt(parts[1], 10, 32)
- if err != nil {
- log.Fatalf("While parsing y component of velocity at line %d: %q", i, line)
- }
- robots.V = append(robots.V, Coord{int(x), int(y)})
- }
- width, height := 11, 7
- counts := make(map[Coord]int)
- // Calculate counts after 100 timesteps
- for i := range robots.P {
- v := robots.V[i]
- for j := 0; j < 100; j++ {
- robots.P[i].x += v.x
- robots.P[i].y += v.y
- }
- wrappedX := addIfNegative(robots.P[i].x%width, width)
- wrappedY := addIfNegative(robots.P[i].y%height, height)
- coord := Coord{wrappedX, wrappedY}
- if _, ok := counts[coord]; !ok {
- counts[coord] = 0
- }
- counts[coord]++
- }
- xmid := width / 2
- ymid := height / 2
- quadrants := make([]int, 4)
- for k, v := range counts {
- if k.x == xmid || k.y == ymid {
- continue
- }
- switch {
- case k.x < xmid && k.y < ymid:
- quadrants[0] += v
- case k.x > xmid && k.y < ymid:
- quadrants[1] += v
- case k.x < xmid && k.y > ymid:
- quadrants[2] += v
- case k.x > xmid && k.y > ymid:
- quadrants[3] += v
- }
- }
- fmt.Printf("%d\n", quadrants[0]*quadrants[1]*quadrants[2]*quadrants[3])
- }
- func addIfNegative(a, b int) int {
- if a < 0 {
- return a + b
- }
- return a
- }
|