Skip to content

Commit f33dc23

Browse files
author
frux
committed
Day 16: Ticket Translation (Part 1 only)
1 parent a7da45f commit f33dc23

File tree

4 files changed

+370
-0
lines changed

4 files changed

+370
-0
lines changed

day16/day16.go

+101
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package day16
2+
3+
import (
4+
"adventofcode-2020/input"
5+
"fmt"
6+
"strconv"
7+
"strings"
8+
)
9+
10+
const INPUT = "./day16/input.txt"
11+
12+
func Part1() string {
13+
entries := input.ReadStrings(INPUT)
14+
fields := []*Field{}
15+
16+
for _, entry := range entries {
17+
if entry == "" {
18+
break
19+
}
20+
21+
fields = append(fields, parseField(entry))
22+
}
23+
24+
myTicketIndex := len(fields) + 2
25+
nearbyTicketsIndex := myTicketIndex + 3
26+
errorRate := 0
27+
28+
for i := nearbyTicketsIndex; i < len(entries); i++ {
29+
ticket := parseTicket(entries[i])
30+
31+
for _, value := range ticket {
32+
if !isValidForAnyField(fields, value) {
33+
errorRate += value
34+
}
35+
}
36+
}
37+
38+
return fmt.Sprint(errorRate)
39+
}
40+
41+
func Part2() string {
42+
return "skipped"
43+
}
44+
45+
func isValidForAnyField(fields []*Field, value int) bool {
46+
for _, field := range fields {
47+
if isValidForField(field, value) {
48+
return true
49+
}
50+
}
51+
52+
return false
53+
}
54+
55+
func isValidForField(field *Field, value int) bool {
56+
for _, limits := range field.Ranges {
57+
if value >= limits[0] && value <= limits[1] {
58+
return true
59+
}
60+
}
61+
62+
return false
63+
}
64+
65+
func parseTicket(line string) []int {
66+
parts := strings.Split(line, ",")
67+
ticket := make([]int, len(parts))
68+
69+
for i, part := range parts {
70+
value, _ := strconv.Atoi(part)
71+
ticket[i] = value
72+
}
73+
74+
return ticket
75+
}
76+
77+
func parseField(line string) *Field {
78+
parts := strings.Split(line, ": ")
79+
return &Field{
80+
Name: parts[0],
81+
Ranges: parseRanges(parts[1]),
82+
}
83+
}
84+
85+
func parseRanges(line string) [][2]int {
86+
parts := strings.Split(line, " or ")
87+
ranges := make([][2]int, len(parts))
88+
for i, part := range parts {
89+
numbers := strings.Split(part, "-")
90+
min, _ := strconv.Atoi(numbers[0])
91+
max, _ := strconv.Atoi(numbers[1])
92+
ranges[i] = [2]int{min, max}
93+
}
94+
95+
return ranges
96+
}
97+
98+
type Field struct {
99+
Name string
100+
Ranges [][2]int
101+
}

0 commit comments

Comments
 (0)