AdventOfCode2020/06/main.go

106 lines
2.3 KiB
Go
Raw Normal View History

2020-12-06 19:00:40 +00:00
package main
import (
"bufio"
"fmt"
"os"
"strings"
2020-12-12 02:57:10 +00:00
"time"
2020-12-06 19:00:40 +00:00
)
func main() {
2020-12-12 02:57:10 +00:00
start := time.Now()
2020-12-06 19:00:40 +00:00
partOne()
2020-12-12 02:57:10 +00:00
duration := time.Since(start)
2020-12-06 19:00:40 +00:00
partTwo()
2020-12-12 02:57:10 +00:00
duration2 := time.Since(start)
fmt.Printf("p1: %s, p2: %s\n", duration, duration2-duration)
2020-12-06 19:00:40 +00:00
}
2020-12-06 19:10:21 +00:00
func union(s string) string {
2020-12-06 19:00:40 +00:00
result := ""
for _, r := range s {
if !strings.ContainsRune(result, r) {
result = result + string(r)
}
}
return result
}
2020-12-06 19:10:21 +00:00
func intersection(s, q string) string {
2020-12-06 19:00:40 +00:00
result := ""
for _, r := range s {
if strings.ContainsRune(q, r) {
result = result + string(r)
}
}
return result
}
// For each of the people in their group, you write down the questions for which they answer "yes", one per line. For example:
// abcx
// abcy
// abcz
// In this group, there are 6 questions to which anyone answered "yes": a, b, c, x, y, and z.
// (Duplicate answers to the same question don't count extra; each question counts at most once.)
// Another group asks for your help, then another, and eventually you've collected answers from every group on the plane (your puzzle input).
// Each group's answers are separated by a blank line, and within each group, each person's answers are on a single line.
func partOne() {
f, _ := os.Open("input")
reader := bufio.NewReader(f)
scanner := bufio.NewScanner(reader)
sum := 0
currentForm := ""
for scanner.Scan() {
line := scanner.Text()
if line == "" {
2020-12-06 19:10:21 +00:00
sum = sum + len(union(currentForm))
2020-12-06 19:00:40 +00:00
currentForm = ""
} else {
currentForm = currentForm + line
}
}
2020-12-06 19:10:21 +00:00
sum = sum + len(union(currentForm))
2020-12-06 19:00:40 +00:00
fmt.Println(sum)
}
// As you finish the last group's customs declaration, you notice that you misread one word in the instructions:
// You don't need to identify the questions to which anyone answered "yes";
// you need to identify the questions to which everyone answered "yes"!
func partTwo() {
f, _ := os.Open("input")
reader := bufio.NewReader(f)
scanner := bufio.NewScanner(reader)
sum := 0
var currentForm string
newgroup := true
for scanner.Scan() {
line := scanner.Text()
if newgroup {
currentForm = line
newgroup = false
} else {
if line != "" {
2020-12-06 19:10:21 +00:00
currentForm = intersection(currentForm, line)
2020-12-06 19:00:40 +00:00
} else {
sum = sum + len(currentForm)
newgroup = true
}
}
}
sum = sum + len(currentForm)
fmt.Println(sum)
}