day21.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. type dish struct {
  10. ingredients []string
  11. allergens []string
  12. }
  13. func readDish(line string) dish {
  14. var food dish
  15. parts := strings.Split(line, " (contains ")
  16. if len(parts) != 2 {
  17. log.Fatalf("Invalid line: %s", line)
  18. }
  19. for _, ing := range strings.Split(parts[0], " ") {
  20. food.ingredients = append(food.ingredients, ing)
  21. }
  22. cleanedPart2 := strings.TrimSuffix(parts[1], ")")
  23. for _, allergen := range strings.Split(cleanedPart2, ", ") {
  24. food.allergens = append(food.allergens, allergen)
  25. }
  26. return food
  27. }
  28. func readFile(file *os.File) []dish {
  29. var foods []dish
  30. scanner := bufio.NewScanner(file)
  31. for scanner.Scan() {
  32. line := scanner.Text()
  33. if line == "" {
  34. break
  35. }
  36. foods = append(foods, readDish(line))
  37. }
  38. if err := scanner.Err(); err != nil {
  39. log.Fatalf("Scanner error: %s", err)
  40. }
  41. return foods
  42. }
  43. type ingredient struct {
  44. count int
  45. possibleAllergens map[string]int
  46. }
  47. func processFoods(foods []dish) map[string]ingredient {
  48. processedIngredients := make(map[string]ingredient)
  49. for _, food := range foods {
  50. for _, item := range food.ingredients {
  51. var currentIngredient ingredient
  52. if _, ok := processedIngredients[item]; !ok {
  53. currentIngredient = ingredient{count: 0, possibleAllergens: make(map[string]int)}
  54. } else {
  55. currentIngredient = processedIngredients[item]
  56. }
  57. currentIngredient.count++
  58. for _, allergen := range food.allergens {
  59. currentIngredient.possibleAllergens[allergen]++
  60. }
  61. processedIngredients[item] = currentIngredient
  62. }
  63. }
  64. return processedIngredients
  65. }
  66. func main() {
  67. if len(os.Args) < 2 {
  68. log.Fatal("You need to specify a file!")
  69. }
  70. filePath := os.Args[1]
  71. file, err := os.Open(filePath)
  72. if err != nil {
  73. log.Fatalf("Failed to open %s!\n", filePath)
  74. }
  75. foods := readFile(file)
  76. if err := file.Close(); err != nil {
  77. log.Fatalf("Failed to close file: %s", err)
  78. }
  79. processedIngredients := processFoods(foods)
  80. fmt.Println(processedIngredients)
  81. }