code.go 863 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. )
  9. func readInput(file *os.File) [3]int {
  10. scanner := bufio.NewScanner(file)
  11. var numbers [3]int
  12. current := 0
  13. for scanner.Scan() {
  14. line := scanner.Text()
  15. if line == "" {
  16. for i := range numbers {
  17. if current > numbers[i] {
  18. current, numbers[i] = numbers[i], current
  19. }
  20. }
  21. current = 0
  22. continue
  23. }
  24. if number, err := strconv.Atoi(line); err == nil {
  25. current += number
  26. } else {
  27. log.Fatal("Numbers: ", err)
  28. }
  29. }
  30. return numbers
  31. }
  32. func main() {
  33. if len(os.Args) < 2 {
  34. log.Fatal("You need to specify a file!")
  35. }
  36. filePath := os.Args[1]
  37. file, err := os.Open(filePath)
  38. if err != nil {
  39. log.Fatalf("Failed to open %s!\n", filePath)
  40. }
  41. numbers := readInput(file)
  42. fmt.Println("Part1:", numbers[0])
  43. fmt.Println("Part2:", numbers[0]+numbers[1]+numbers[2])
  44. }