AdventOfCode2020/06/main.go

106 lines
2.3 KiB
Go

package main
import (
"bufio"
"fmt"
"os"
"strings"
"time"
)
func main() {
start := time.Now()
partOne()
duration := time.Since(start)
partTwo()
duration2 := time.Since(start)
fmt.Printf("p1: %s, p2: %s\n", duration, duration2-duration)
}
func union(s string) string {
result := ""
for _, r := range s {
if !strings.ContainsRune(result, r) {
result = result + string(r)
}
}
return result
}
func intersection(s, q string) string {
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 == "" {
sum = sum + len(union(currentForm))
currentForm = ""
} else {
currentForm = currentForm + line
}
}
sum = sum + len(union(currentForm))
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 != "" {
currentForm = intersection(currentForm, line)
} else {
sum = sum + len(currentForm)
newgroup = true
}
}
}
sum = sum + len(currentForm)
fmt.Println(sum)
}