code.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 {
  11. content, err := ioutil.ReadFile(file)
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. lines := strings.Split(string(content), "\n")
  16. var input []int
  17. for _, line := range lines {
  18. if line == "" {
  19. continue
  20. }
  21. if number, err := strconv.Atoi(line); err == nil {
  22. input = append(input, number)
  23. } else {
  24. log.Fatal(err)
  25. }
  26. }
  27. return input
  28. }
  29. func part1(input []int) int {
  30. increase := 0
  31. for i := 1; i < len(input); i++ {
  32. if input[i-1] < input[i] {
  33. increase++
  34. }
  35. }
  36. return increase
  37. }
  38. func part2(input []int) []int {
  39. var measurements []int
  40. index := 0
  41. for i, value := range input {
  42. if i+2 < len(input) {
  43. measurements = append(measurements, value)
  44. measurements[index] += input[i+1]
  45. measurements[index] += input[i+2]
  46. index++
  47. }
  48. }
  49. return measurements
  50. }
  51. func main() {
  52. if len(os.Args) < 2 {
  53. log.Fatal("Please provide a file name as argument")
  54. }
  55. input := readInput(os.Args[1])
  56. fmt.Println("Part 1:", part1(input))
  57. fmt.Println("Part 2:", part1(part2(input)))
  58. }