Skip to content

Instantly share code, notes, and snippets.

@felix-larsen
Created December 21, 2020 09:15
Show Gist options
  • Save felix-larsen/72e6b11d1e014ac66f565855c66dceff to your computer and use it in GitHub Desktop.
Save felix-larsen/72e6b11d1e014ac66f565855c66dceff to your computer and use it in GitHub Desktop.
21th December solution - Advent of Code 2020 - swift
let allPotIngredients = allergiesToIngredients.map{ $0.value }.reduce(Set<String>()) { (all, set) -> Set<String> in
all.union(set)
}
let result = foods.map { $0.0.subtracting(allPotIngredients).count }.reduce(0, +)
print(result)
var removedAValue = true
while removedAValue {
removedAValue = false
for (_, ingredients) in allergiesToIngredients {
if ingredients.count == 1 {
for a in allergiesToIngredients {
let countBefore = a.value.count
if a.value.count > 1 {
let filteredIngredients = a.value.filter { $0 != ingredients.first!}
allergiesToIngredients[a.key] = filteredIngredients
if countBefore != filteredIngredients.count {
removedAValue = true
}
}
}
}
}
}
let sortedByAllergyNames = allergiesToIngredients.sorted { (ele1, ele2) -> Bool in
ele1.key < ele2.key
}
print(sortedByAllergyNames.map { $0.value.first!}.joined(separator: ","))
let filename = "/Users/felix/xCodeProjects/AdventOfCode2020.playground/Resources/december21.txt"
let contents = try! String(contentsOfFile: filename)
let lines = contents.components(separatedBy: CharacterSet.newlines).filter { !$0.isEmpty}
var foods = [(Set<String>, Set<String>)]()
for line in lines {
let parts = line.components(separatedBy: " (contains ")
let ingredients = parts[0].components(separatedBy: " ")
let allergies = String(parts[1].dropLast()).components(separatedBy: ", ")
foods.append((Set(ingredients), Set(allergies)))
}
let allAllergies = foods.map{$1}.reduce(Set<String>()) { (allerges, set) -> Set<String> in
allerges.union(set)
}
var allergiesToIngredients = [String : Set<String>]()
for allergy in allAllergies {
var ingredients: Set<String>? = nil
for food in foods {
if food.1.contains(allergy) {
if ingredients == nil {
ingredients = food.0
} else {
ingredients = ingredients?.intersection(food.0)
}
}
}
allergiesToIngredients[allergy] = ingredients
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment