summaryrefslogtreecommitdiff
path: root/day14/main.go
blob: a4a2da2fc99df037d961f77c131bdea4ca8fe92c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	fmt.Println(part1(readData("example.txt"), 11, 7), 12)
	fmt.Println(part1(readData("data.txt"), 101, 103))
	part2(readData("data.txt"), 101, 103)
}

type Bot struct {
	x, y   int
	dx, dy int
}

func part1(bots []Bot, w, h int) int {
	q1, q2, q3, q4 := 0, 0, 0, 0
	hw := w / 2
	hh := h / 2

	for _, b := range bots {
		x := ((b.x+b.dx*100)%w + w) % w
		y := ((b.y+b.dy*100)%h + h) % h

		if x > hw {
			if y < hh {
				q2++
			} else if y > hh {
				q4++
			}
		} else if x < hw {
			if y < hh {
				q1++
			} else if y > hh {
				q3++
			}
		}
	}

	return q1 * q2 * q3 * q4
}

func part2(bots []Bot, w, h int) {
	fp, err := os.Create("output.txt")
	if err != nil {
		panic(err)
	}

	buffer := make([]byte, (w+1)*h)
	for y := range h {
		buffer[y*(w+1)+w] = '\n'
	}

	for i := range 10000 {
		for y := range h {
			for x := range w {
				buffer[y*(w+1)+x] = ' '
			}
		}

		for _, b := range bots {
			x := ((b.x+b.dx*i)%w + w) % w
			y := ((b.y+b.dy*i)%h + h) % h
			buffer[y*(w+1)+x] = 'X'
		}

		// So fucking stupid
		if strings.Index(string(buffer), "XXXXXXXX") >= 0 {
			fmt.Println(i)
			fmt.Fprintln(fp, i)
			fp.Write(buffer)
		}
	}
}

func parsePair(s string) (x, y int) {
	nums := strings.Split(s[2:], ",")
	x, _ = strconv.Atoi(nums[0])
	y, _ = strconv.Atoi(nums[1])
	return
}

func readData(fileName string) (bots []Bot) {
	fp, _ := os.Open(fileName)
	scanner := bufio.NewScanner(fp)

	for scanner.Scan() {
		line := strings.Split(strings.TrimSpace(scanner.Text()), " ")
		x, y := parsePair(line[0])
		dx, dy := parsePair(line[1])
		bots = append(bots, Bot{x, y, dx, dy})
	}
	return
}