code.go 1.8 KB

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