code.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. func readInput(file *os.File) [][]byte {
  9. scanner := bufio.NewScanner(file)
  10. var platform [][]byte
  11. for scanner.Scan() {
  12. line := scanner.Text()
  13. if line == "" {
  14. break
  15. }
  16. var row []byte
  17. for i := range line {
  18. row = append(row, line[i])
  19. }
  20. platform = append(platform, row)
  21. }
  22. return platform
  23. }
  24. func tiltNorth(platform [][]byte, y int, x int, height int, width int) bool {
  25. change := false
  26. for {
  27. prevY := y - 1
  28. if prevY < 0 || platform[prevY][x] == '#' || platform[prevY][x] == 'O' {
  29. break
  30. }
  31. platform[y][x] = '.'
  32. platform[prevY][x] = 'O'
  33. change = true
  34. y--
  35. }
  36. return change
  37. }
  38. func tiltPlatform(platform [][]byte, direction func([][]byte, int, int, int, int) bool, height int, width int) bool {
  39. change := false
  40. for y := range platform {
  41. for x := range platform[y] {
  42. if platform[y][x] == 'O' {
  43. if direction(platform, y, x, height, width) {
  44. change = true
  45. }
  46. }
  47. }
  48. }
  49. return change
  50. }
  51. func part1(platform [][]byte) int {
  52. height := len(platform)
  53. width := len(platform[0])
  54. tiltPlatform(platform, tiltNorth, height, width)
  55. var result int
  56. for y := range platform {
  57. for x := range platform[y] {
  58. if platform[y][x] == 'O' {
  59. result += height - y
  60. }
  61. }
  62. }
  63. return result
  64. }
  65. func main() {
  66. if len(os.Args) < 2 {
  67. log.Fatal("You need to specify a file!")
  68. }
  69. filePath := os.Args[1]
  70. file, err := os.Open(filePath)
  71. if err != nil {
  72. log.Fatalf("Failed to open %s!\n", filePath)
  73. }
  74. platform := readInput(file)
  75. fmt.Println("Part1:", part1(platform))
  76. }