adventofcode/2017/day04/day04.go

81 lines
1.2 KiB
Go
Raw Permalink Normal View History

2017-12-04 12:49:31 +00:00
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
inp := StdinToStrings()
part1(inp)
part2(inp)
}
2017-12-04 12:54:33 +00:00
func findValid(inp []string, cmp func(string, string) bool) {
2017-12-04 12:49:31 +00:00
cnt := 0
for _, v := range inp {
wrds := strings.Split(v, " ")
isGood := true
for i := range wrds {
for j := i + 1; j < len(wrds); j++ {
2017-12-04 12:54:33 +00:00
if cmp(wrds[i], wrds[j]) {
2017-12-04 12:49:31 +00:00
isGood = false
}
if !isGood {
break
}
}
if !isGood {
break
}
}
if isGood {
cnt++
}
}
fmt.Println("Valid Passphrases:", cnt)
}
2017-12-04 12:54:33 +00:00
func part1(inp []string) {
fmt.Println("== Part 1 ==")
cmp := func(wrd1, wrd2 string) bool {
return wrd1 == wrd2
}
findValid(inp, cmp)
}
2017-12-04 12:49:31 +00:00
func part2(inp []string) {
fmt.Println("== Part 2 ==")
2017-12-04 12:54:33 +00:00
cmp := func(wrd1, wrd2 string) bool {
return isAnagram(wrd1, wrd2)
2017-12-04 12:49:31 +00:00
}
2017-12-04 12:54:33 +00:00
findValid(inp, cmp)
2017-12-04 12:49:31 +00:00
}
func isAnagram(wrd1, wrd2 string) bool {
charMap := make(map[byte]int)
for i := range wrd1 {
charMap[wrd1[i]]++
}
for i := range wrd2 {
charMap[wrd2[i]]--
}
for _, v := range charMap {
if v != 0 {
return false
}
}
return true
}
func StdinToStrings() []string {
var input []string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
input = append(input, scanner.Text())
}
return input
}