code.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. const Time = "Time: "
  10. const Distance = "Distance: "
  11. type Paper struct {
  12. matrix [][]int
  13. bigMatrix [][]int
  14. }
  15. func readInput(file *os.File) Paper {
  16. scanner := bufio.NewScanner(file)
  17. var paper Paper
  18. for scanner.Scan() {
  19. line := scanner.Text()
  20. if line == "" {
  21. break
  22. }
  23. if strings.HasPrefix(line, Time) {
  24. line = strings.TrimLeft(line, Time)
  25. } else {
  26. line = strings.TrimLeft(line, Distance)
  27. }
  28. parts := strings.Split(line, " ")
  29. if len(parts) == 0 {
  30. log.Fatalf("Wrong input: %s", line)
  31. }
  32. var numbers []int
  33. var numberString string
  34. for i := range parts {
  35. if parts[i] == "" {
  36. continue
  37. }
  38. numberString += parts[i]
  39. var number int
  40. n, err := fmt.Sscanf(parts[i], "%d", &number)
  41. if n != 1 || err != nil {
  42. log.Fatalf("Failed to read number: %s\n%s", parts[i], err)
  43. }
  44. numbers = append(numbers, number)
  45. }
  46. var bigNumber int
  47. n, err := fmt.Sscanf(numberString, "%d", &bigNumber)
  48. if n != 1 || err != nil {
  49. log.Fatalf("Failed to read number: %s\n%s", numberString, err)
  50. }
  51. paper.bigMatrix = append(paper.bigMatrix, []int{bigNumber})
  52. paper.matrix = append(paper.matrix, numbers)
  53. if len(paper.matrix) == 2 {
  54. break
  55. }
  56. }
  57. return paper
  58. }
  59. func part1(matrix [][]int) int {
  60. result := 1
  61. for i := range matrix[0] {
  62. min := matrix[1][i] / matrix[0][i]
  63. for {
  64. if min*(matrix[0][i]-min) > matrix[1][i] {
  65. break
  66. }
  67. min++
  68. }
  69. result *= matrix[0][i] - min - min + 1
  70. }
  71. return result
  72. }
  73. func main() {
  74. if len(os.Args) < 2 {
  75. log.Fatal("You need to specify a file!")
  76. }
  77. filePath := os.Args[1]
  78. file, err := os.Open(filePath)
  79. if err != nil {
  80. log.Fatalf("Failed to open %s!\n", filePath)
  81. }
  82. paper := readInput(file)
  83. fmt.Println("Part1:", part1(paper.matrix))
  84. fmt.Println("Part2:", part1(paper.bigMatrix))
  85. }