code.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. type octo struct {
  11. value int
  12. flashed bool
  13. }
  14. func readInput(file string) [][]octo {
  15. content, err := ioutil.ReadFile(file)
  16. if err != nil {
  17. log.Fatal(err)
  18. }
  19. lines := strings.Split(string(content), "\n")
  20. var input [][]octo
  21. for _, line := range lines {
  22. if line == "" {
  23. continue
  24. }
  25. var row []octo
  26. for _, char := range line {
  27. if number, err := strconv.Atoi(string(char)); err == nil {
  28. row = append(row, octo{number, false})
  29. } else {
  30. log.Fatal(err)
  31. }
  32. }
  33. input = append(input, row)
  34. }
  35. return input
  36. }
  37. func doNeighbors(input [][]octo, x, y int) int {
  38. var neighbors int
  39. for i := -1; i <= 1; i++ {
  40. for j := -1; j <= 1; j++ {
  41. if i == 0 && j == 0 {
  42. continue
  43. }
  44. if x+i < 0 || x+i >= len(input[y]) {
  45. continue
  46. }
  47. if y+j < 0 || y+j >= len(input) {
  48. continue
  49. }
  50. if !input[y+j][x+i].flashed {
  51. input[y+j][x+i].value++
  52. if input[y+j][x+i].value > 9 {
  53. input[y+j][x+i].value = 0
  54. input[y+j][x+i].flashed = true
  55. neighbors++
  56. neighbors += doNeighbors(input, x+i, y+j)
  57. }
  58. }
  59. }
  60. }
  61. return neighbors
  62. }
  63. func part1(input [][]octo) int {
  64. var flashed int
  65. for i := 0; i < 10; i++ {
  66. for y, row := range input {
  67. for x, _ := range row {
  68. if input[y][x].flashed {
  69. input[y][x].flashed = false
  70. }
  71. input[y][x].value++
  72. if input[y][x].value > 9 {
  73. input[y][x].value = 0
  74. input[y][x].flashed = true
  75. flashed++
  76. flashed += doNeighbors(input, x, y)
  77. }
  78. }
  79. }
  80. }
  81. return flashed
  82. }
  83. func main() {
  84. if len(os.Args) < 2 {
  85. log.Fatal("Please provide a file name as argument")
  86. }
  87. input := readInput(os.Args[1])
  88. fmt.Println(part1(input))
  89. }