Skip to content

Instantly share code, notes, and snippets.

@felix-larsen
Created December 6, 2020 09:01
Show Gist options
  • Save felix-larsen/b986e981787f3bc2f5d8d9841a1a1e85 to your computer and use it in GitHub Desktop.
Save felix-larsen/b986e981787f3bc2f5d8d9841a1a1e85 to your computer and use it in GitHub Desktop.
6th December solution - Advent of Code - swift
let solution = solve(lines, isFirstPuzzle: true)
print(solution)
let solution = solve(lines, isFirstPuzzle: false)
print(solution)
let filename = "/Users/felix/xCodeProjects/AdventOfCode2020.playground/Resources/december06.txt"
let contents = try! String(contentsOfFile: filename)
let lines = contents.components(separatedBy: CharacterSet.newlines)
func solve(_ lines: [String], isFirstPuzzle: Bool) -> Int {
var group: Set<String.Element>? = nil
var groups = [Set<String.Element>]()
lines.forEach { (line) in
if line.isEmpty {
if let group = group {
groups.append(group)
}
group = nil
} else {
if let groupNonNil = group {
if isFirstPuzzle {
group = groupNonNil.union(Set(line))
} else {
group = groupNonNil.intersection(Set(line))
}
} else {
group = Set(line)
}
}
}
let elementsCount = groups.reduce(0) { (sum, nextSet) -> Int in
sum + nextSet.count
}
return elementsCount
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment