|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "sort" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/markkovari/advent_of_code/aoc-go-common" |
| 9 | +) |
| 10 | + |
| 11 | +type Day04 struct{} |
| 12 | + |
| 13 | +func (d Day04) Part1(input string) string { |
| 14 | + countValid := 0 |
| 15 | + for _, line := range strings.Split(input, "\n") { |
| 16 | + if line == "" { continue } |
| 17 | + words := strings.Fields(line) |
| 18 | + frequency := make(map[string]int) |
| 19 | + valid := true |
| 20 | + for _, word := range words { |
| 21 | + frequency[word]++ |
| 22 | + if frequency[word] > 1 { |
| 23 | + valid = false |
| 24 | + break |
| 25 | + } |
| 26 | + } |
| 27 | + if valid { countValid++ } |
| 28 | + } |
| 29 | + return fmt.Sprintf("%d", countValid) |
| 30 | +} |
| 31 | + |
| 32 | +func (d Day04) Part2(input string) string { |
| 33 | + countValid := 0 |
| 34 | + for _, line := range strings.Split(input, "\n") { |
| 35 | + if line == "" { continue } |
| 36 | + words := strings.Fields(line) |
| 37 | + if !hasAnagram(words) { |
| 38 | + countValid++ |
| 39 | + } |
| 40 | + } |
| 41 | + return fmt.Sprintf("%d", countValid) |
| 42 | +} |
| 43 | + |
| 44 | +func hasAnagram(words []string) bool { |
| 45 | + sortedWords := make([]string, len(words)) |
| 46 | + for i, word := range words { |
| 47 | + chars := strings.Split(word, "") |
| 48 | + sort.Strings(chars) |
| 49 | + sortedWords[i] = strings.Join(chars, "") |
| 50 | + } |
| 51 | + for i := 0; i < len(sortedWords); i++ { |
| 52 | + for j := i + 1; j < len(sortedWords); j++ { |
| 53 | + if sortedWords[i] == sortedWords[j] { |
| 54 | + return true |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + return false |
| 59 | +} |
| 60 | + |
| 61 | +func main() { |
| 62 | + common.Run(2017, 4, Day04{}) |
| 63 | +} |
0 commit comments