10b
This commit is contained in:
parent
b2afe310b4
commit
d751bc64f8
@ -20,28 +20,40 @@ struct Day10: Runnable {
|
|||||||
//.map { line in line.map { $0.wholeNumberValue! } }
|
//.map { line in line.map { $0.wholeNumberValue! } }
|
||||||
var s = Deque<String.Element>()
|
var s = Deque<String.Element>()
|
||||||
var illegalCharacters = [String.Element]()
|
var illegalCharacters = [String.Element]()
|
||||||
|
var autocompleteScores = [Int]()
|
||||||
for (lineNumber, line) in lines.enumerated() {
|
for (lineNumber, line) in lines.enumerated() {
|
||||||
|
s = Deque<String.Element>()
|
||||||
|
var isIllegalLine = false
|
||||||
for char in line {
|
for char in line {
|
||||||
if char.isClosing {
|
if char.isClosing {
|
||||||
if let popped = s.popFirst() {
|
guard let popped = s.popFirst() else {
|
||||||
if let shouldBeClosedBy = popped.closedBy {
|
fatalError()
|
||||||
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 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)
|
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(illegalCharacters.map{$0.score!}.reduce(0,+))
|
||||||
|
print(autocompleteScores.sorted()[autocompleteScores.count / 2])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -78,4 +90,19 @@ extension String.Element {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var autocompleteScore: Int? {
|
||||||
|
switch self {
|
||||||
|
case ")":
|
||||||
|
return 1
|
||||||
|
case "]":
|
||||||
|
return 2
|
||||||
|
case "}":
|
||||||
|
return 3
|
||||||
|
case ">":
|
||||||
|
return 4
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user