solve_2.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. type coord struct {
  8. x,y,nb_neighbors int
  9. }
  10. func update_neighbors_insertion(positions* []*coord, i,j int) int{
  11. nbn := 0
  12. for _, paper_roll := range *positions {
  13. switch(paper_roll.x){
  14. case i:
  15. switch(paper_roll.y){
  16. case j-1, j+1:
  17. nbn++
  18. paper_roll.nb_neighbors++
  19. }
  20. case i-1, i+1:
  21. switch(paper_roll.y){
  22. case j-1,j,j+1:
  23. nbn++
  24. paper_roll.nb_neighbors++
  25. }
  26. }
  27. }
  28. return nbn
  29. }
  30. func continue_removing(positions* []*coord){
  31. for i:=0; i < len(*positions); {
  32. paper_roll := (*positions)[i]
  33. if paper_roll.nb_neighbors < 4 {
  34. (*positions)[i] = (*positions)[len(*positions)-1]
  35. (*positions)[len(*positions)-1] = nil
  36. *positions = (*positions)[:len(*positions)-1]
  37. } else {
  38. i++
  39. }
  40. }
  41. }
  42. func main() {
  43. fmt.Println("Advent of Code 2025 - Day 4 - Part 2")
  44. f,_ := os.Open("4/input")
  45. defer f.Close()
  46. var positions []*coord
  47. scanner := bufio.NewScanner(f)
  48. line_num := 0
  49. for scanner.Scan() {
  50. line := scanner.Text()
  51. for i:= 0; i < len(line); i++{
  52. if line[i] == '@'{
  53. nbn := update_neighbors_insertion(&positions,line_num,i)
  54. positions = append(positions, &coord{line_num,i,nbn})
  55. }
  56. }
  57. line_num++
  58. }
  59. paper_rolls_pre := len(positions)
  60. for {
  61. loop_entry_paper_rolls := len(positions)
  62. // remove paper_rolls with less than 4 neighbors
  63. continue_removing(&positions)
  64. update_neighbors_after_removal(&positions)
  65. // if nothing was removed break from loop
  66. if loop_entry_paper_rolls == len(positions) {
  67. break
  68. }
  69. }
  70. fmt.Println(paper_rolls_pre - len(positions))
  71. }
  72. func update_neighbors_after_removal(positions* []*coord){
  73. // reset nb_neighbors
  74. for _, paper_roll := range *positions{
  75. paper_roll.nb_neighbors = 0
  76. }
  77. // update nb_neighbors
  78. for _, paper_roll := range *positions{
  79. x,y := paper_roll.x, paper_roll.y
  80. for _, npar := range *positions {
  81. if &npar != &paper_roll{
  82. switch(npar.x){
  83. case x+1, x-1:
  84. switch(npar.y){
  85. case y, y+1, y-1:
  86. paper_roll.nb_neighbors++
  87. }
  88. case x:
  89. switch(npar.y){
  90. case y+1, y-1:
  91. paper_roll.nb_neighbors++
  92. }
  93. }
  94. }
  95. }
  96. }
  97. }