code.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. func readInput(file string) (map[string]int, map[string][]string) {
  10. content, err := ioutil.ReadFile(file)
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. lines := strings.Split(string(content), "\n")
  15. template := make(map[string]int)
  16. input := make(map[string][]string)
  17. readingTemplate := true
  18. for _, line := range lines {
  19. if line == "" {
  20. readingTemplate = false
  21. continue
  22. }
  23. if readingTemplate {
  24. for i := 0; i < len(line)-1; i++ {
  25. template[string(line[i:i+2])] += 1
  26. }
  27. continue
  28. }
  29. parts := strings.Split(line, " -> ")
  30. if len(parts) != 2 {
  31. log.Fatal("Invalid line: ", line)
  32. }
  33. input[parts[0]] = []string{fmt.Sprintf("%c%s", parts[0][0], parts[1]), fmt.Sprintf("%s%c", parts[1], parts[0][1])}
  34. }
  35. return template, input
  36. }
  37. func countElements(template map[string]int) (int, int) {
  38. counts := make(map[byte]int)
  39. for k, v := range template {
  40. counts[k[0]] += v
  41. counts[k[1]] += v
  42. }
  43. smallest := counts['N']
  44. largest := counts['N']
  45. for _, c := range counts {
  46. if c < smallest {
  47. smallest = c
  48. }
  49. if c > largest {
  50. largest = c
  51. }
  52. }
  53. return smallest, largest
  54. }
  55. func part1(template map[string]int, input map[string][]string) (map[string]int, int) {
  56. for i := 0; i < 10; i++ {
  57. newTemplate := make(map[string]int)
  58. for k, v1 := range template {
  59. for _, v2 := range input[k] {
  60. newTemplate[v2] += v1
  61. }
  62. }
  63. template = newTemplate
  64. }
  65. smallest, largest := countElements(template)
  66. fmt.Println(smallest, largest)
  67. return template, largest - smallest
  68. }
  69. func main() {
  70. if len(os.Args) < 2 {
  71. log.Fatal("Please provide a file name as argument")
  72. }
  73. template, input := readInput(os.Args[1])
  74. var diff int
  75. _, diff = part1(template, input)
  76. fmt.Println("Part1:", diff)
  77. //fmt.Println("Part1:", part2(template, input))
  78. }