code.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 part2(entry string, devices map[string][]string, dac, fft bool) int {
  38. if entry == "out" {
  39. if dac && fft {
  40. return 1
  41. }
  42. return 0
  43. }
  44. if entry == "dac" {
  45. dac = true
  46. }
  47. if entry == "fft" {
  48. fft = true
  49. }
  50. var count int
  51. for _, device := range devices[entry] {
  52. count += part2(device, devices, dac, fft)
  53. }
  54. return count
  55. }
  56. func main() {
  57. if len(os.Args) < 2 {
  58. log.Fatal("You need to specify a file!")
  59. }
  60. filePath := os.Args[1]
  61. file, err := os.Open(filePath)
  62. if err != nil {
  63. log.Fatalf("Failed to open %s!\n", filePath)
  64. }
  65. devices := readInput(file)
  66. fmt.Println("Part1:", part1("you", devices))
  67. fmt.Println("Part2:", part2("svr", devices, false, false))
  68. }