code.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. func readInput(file string) (int, int) {
  11. content, err := ioutil.ReadFile(file)
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. lines := strings.Split(string(content), "\n")
  16. if len(lines) != 2 {
  17. log.Fatal("expected 2 lines")
  18. }
  19. partsFirstLine := strings.Split(lines[0], ": ")
  20. if len(partsFirstLine) != 2 {
  21. log.Fatal("expected 2 parts")
  22. }
  23. player1, err := strconv.Atoi(partsFirstLine[1])
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. partsSecondLine := strings.Split(lines[1], ": ")
  28. if len(partsSecondLine) != 2 {
  29. log.Fatal("expected 2 parts")
  30. }
  31. player2, err := strconv.Atoi(partsSecondLine[1])
  32. if err != nil {
  33. log.Fatal(err)
  34. }
  35. return player1, player2
  36. }
  37. var dice int
  38. func roll() int {
  39. dice++
  40. return dice
  41. }
  42. func part1(player1, player2 int) int {
  43. var score1, score2 int
  44. first := true
  45. countDice := 0
  46. for {
  47. if score1 >= 1000 || score2 >= 1000 {
  48. break
  49. }
  50. if first {
  51. player1 = (roll() + roll() + roll() + player1) % 10
  52. if player1 == 0 {
  53. player1 = 10
  54. }
  55. score1 += player1
  56. first = false
  57. countDice += 3
  58. } else {
  59. player2 = (roll() + roll() + roll() + player2) % 10
  60. if player2 == 0 {
  61. player2 = 10
  62. }
  63. score2 += player2
  64. first = true
  65. countDice += 3
  66. }
  67. }
  68. if score1 > score2 {
  69. return score2 * countDice
  70. }
  71. return score1 * countDice
  72. }
  73. func main() {
  74. if len(os.Args) < 2 {
  75. log.Fatal("Please provide a file name as argument")
  76. }
  77. player1, player2 := readInput(os.Args[1])
  78. dice = 0
  79. fmt.Println("Part1:", part1(player1, player2))
  80. }