code.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. computers := make(map[string][]string)
  12. for scanner.Scan() {
  13. line := scanner.Text()
  14. if line == "" {
  15. break
  16. }
  17. parts := strings.Split(line, "-")
  18. if len(parts) != 2 {
  19. log.Fatalf("Bad input: %s", line)
  20. }
  21. computers[parts[0]] = append(computers[parts[0]], parts[1])
  22. computers[parts[1]] = append(computers[parts[1]], parts[0])
  23. }
  24. return computers
  25. }
  26. func getSets(computers map[string][]string) [][]string {
  27. var sets [][]string
  28. for key, value := range computers {
  29. if key[0] != 't' {
  30. continue
  31. }
  32. for i := range value {
  33. for _, subKey := range computers[value[i]] {
  34. if subKey == key {
  35. continue
  36. }
  37. subValues := computers[subKey]
  38. for j := range subValues {
  39. if subValues[j] == key {
  40. sets = append(sets, []string{key, value[i], subKey})
  41. }
  42. }
  43. }
  44. }
  45. }
  46. return sets
  47. }
  48. func main() {
  49. if len(os.Args) < 2 {
  50. log.Fatal("You need to specify a file!")
  51. }
  52. filePath := os.Args[1]
  53. file, err := os.Open(filePath)
  54. if err != nil {
  55. log.Fatalf("Failed to open %s!\n", filePath)
  56. }
  57. computers := readInput(file)
  58. fmt.Println(getSets(computers))
  59. }