code.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. func readInput(file string) map[int]int {
  11. content, err := ioutil.ReadFile(file)
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. fishStrings := strings.Split(string(content), ",")
  16. input := make(map[int]int)
  17. for _, fishString := range fishStrings {
  18. if fishString == "" {
  19. continue
  20. }
  21. if number, err := strconv.Atoi(fishString); err == nil {
  22. input[number]++
  23. } else {
  24. log.Fatal(err)
  25. }
  26. }
  27. return input
  28. }
  29. func breed(fish map[int]int, days int) int {
  30. for d := 0; d < days; d++ {
  31. newFish := make(map[int]int)
  32. for k, v := range fish {
  33. if k == 0 {
  34. newFish[8] = v
  35. newFish[6] += v
  36. continue
  37. }
  38. newFish[k-1] += v
  39. }
  40. fish = newFish
  41. }
  42. sum := 0
  43. for _, v := range fish {
  44. sum += v
  45. }
  46. return sum
  47. }
  48. func main() {
  49. if len(os.Args) < 2 {
  50. log.Fatal("Please provide a file name as argument")
  51. }
  52. input := readInput(os.Args[1])
  53. fmt.Println("Part 1:", breed(input, 80))
  54. fmt.Println("Part 2:", breed(input, 256))
  55. }