day11.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "bufio"
  4. "flag"
  5. "fmt"
  6. "os"
  7. "strconv"
  8. "strings"
  9. "time"
  10. )
  11. func main() {
  12. example := flag.Bool("example", false, "example or input")
  13. flag.Parse()
  14. filename := "input.txt"
  15. if *example {
  16. filename = "example.txt"
  17. }
  18. file, err := os.Open(filename)
  19. if err != nil {
  20. fmt.Println("Ошибка при открытии файла:", err)
  21. return
  22. }
  23. defer file.Close()
  24. scanner := bufio.NewScanner(file)
  25. scanner.Scan()
  26. line := scanner.Text()
  27. stones := parseInput(line)
  28. // part 1
  29. start := time.Now()
  30. steps := 25
  31. result := simulateBlinks(stones, steps)
  32. end1 := time.Since(start)
  33. fmt.Println("Total count of stones after", steps, "steps:", len(result), "in time:", end1)
  34. }
  35. func parseInput(input string) []int {
  36. parts := strings.Fields(input)
  37. stones := make([]int, len(parts))
  38. for i, part := range parts {
  39. stones[i], _ = strconv.Atoi(part)
  40. }
  41. return stones
  42. }
  43. func simulateBlinks(stones []int, steps int) []int {
  44. for step := 0; step < steps; step++ {
  45. var newStones []int
  46. for _, stone := range stones {
  47. if stone == 0 {
  48. newStones = append(newStones, 1)
  49. } else if len(strconv.Itoa(stone))%2 == 0 {
  50. left, right := splitStone(stone)
  51. newStones = append(newStones, left, right)
  52. } else {
  53. newStones = append(newStones, stone*2024)
  54. }
  55. }
  56. stones = newStones
  57. }
  58. return stones
  59. }
  60. func splitStone(stone int) (int, int) {
  61. str := strconv.Itoa(stone)
  62. mid := len(str) / 2
  63. left, _ := strconv.Atoi(str[:mid])
  64. right, _ := strconv.Atoi(str[mid:])
  65. return left, right
  66. }