This commit is contained in:
Max Nuding 2021-12-10 07:33:51 +01:00
parent b2afe310b4
commit d751bc64f8
Signed by: phlaym
GPG Key ID: A06651BAB6777237

View File

@ -20,28 +20,40 @@ struct Day10: Runnable {
//.map { line in line.map { $0.wholeNumberValue! } }
var s = Deque<String.Element>()
var illegalCharacters = [String.Element]()
var autocompleteScores = [Int]()
for (lineNumber, line) in lines.enumerated() {
s = Deque<String.Element>()
var isIllegalLine = false
for char in line {
if char.isClosing {
if let popped = s.popFirst() {
if let shouldBeClosedBy = popped.closedBy {
if shouldBeClosedBy == char {
continue // Valid chunk
}
print("Line: \(lineNumber): Expected \(shouldBeClosedBy), but found \(char) instead")
illegalCharacters.append(char)
break
} else {
print("\(popped) should be an opening character, but cannot find a fitting closing char. Line: \(lineNumber+1), char: \(char)")
}
} else {
print("Found closing character \(char), but empty list!")
guard let popped = s.popFirst() else {
fatalError()
}
guard let shouldBeClosedBy = popped.closedBy else {
fatalError()
}
if shouldBeClosedBy == char {
continue // Valid chunk
}
//print("Line: \(lineNumber): Expected \(shouldBeClosedBy), but found \(char) instead")
illegalCharacters.append(char)
isIllegalLine = true
break
}
s.prepend(char)
}
if !isIllegalLine {
var lineScore = 0
s.reverse()
while let last = s.popLast() {
let charValue = last.closedBy!.autocompleteScore!
lineScore = lineScore * 5 + charValue
}
autocompleteScores.append(lineScore)
}
}
print(illegalCharacters.map{$0.score!}.reduce(0,+))
print(autocompleteScores.sorted()[autocompleteScores.count / 2])
}
@ -78,4 +90,19 @@ extension String.Element {
return nil
}
}
var autocompleteScore: Int? {
switch self {
case ")":
return 1
case "]":
return 2
case "}":
return 3
case ">":
return 4
default:
return nil
}
}
}