code.go 984 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. func readInput(file *os.File) map[string][]string {
  10. scanner := bufio.NewScanner(file)
  11. devices := make(map[string][]string)
  12. for scanner.Scan() {
  13. line := scanner.Text()
  14. if line == "" {
  15. continue
  16. }
  17. parts := strings.Split(line, ": ")
  18. if len(parts) < 2 {
  19. log.Fatalf("Bad input: %s", line)
  20. }
  21. name := parts[0]
  22. connections := strings.Split(parts[1], " ")
  23. devices[name] = connections
  24. }
  25. return devices
  26. }
  27. func part1(entry string, devices map[string][]string) int {
  28. if entry == "out" {
  29. return 1
  30. }
  31. var count int
  32. for _, device := range devices[entry] {
  33. count += part1(device, devices)
  34. }
  35. return count
  36. }
  37. func main() {
  38. if len(os.Args) < 2 {
  39. log.Fatal("You need to specify a file!")
  40. }
  41. filePath := os.Args[1]
  42. file, err := os.Open(filePath)
  43. if err != nil {
  44. log.Fatalf("Failed to open %s!\n", filePath)
  45. }
  46. devices := readInput(file)
  47. fmt.Println("Part1:", part1("you", devices))
  48. }