d13
This commit is contained in:
50
day13/d13p2.swift
Normal file
50
day13/d13p2.swift
Normal file
@@ -0,0 +1,50 @@
|
||||
import Foundation
|
||||
|
||||
struct Machine {
|
||||
let (aX, aY): (Int, Int)
|
||||
let (bX, bY): (Int, Int)
|
||||
let (przX, przY): (Int, Int)
|
||||
func solve() -> Int? {
|
||||
let d = aX*bY - aY*bX
|
||||
let (a, ar) = (przX*bY - przY*bX).quotientAndRemainder(dividingBy: d)
|
||||
let (b, br) = (przY*aX - przX*aY).quotientAndRemainder(dividingBy: d)
|
||||
if ar == 0 && br == 0 {
|
||||
return a*3 + b
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func readInput(_ filePath: String) throws -> [Machine] {
|
||||
let btnA = try Regex(#"Button A: X\+([0-9]+), Y\+([0-9]+)"#)
|
||||
let btnB = try Regex(#"Button B: X\+([0-9]+), Y\+([0-9]+)"#)
|
||||
let prize = try Regex(#"Prize: X=([0-9]+), Y=([0-9]+)"#)
|
||||
|
||||
let content = try String(contentsOfFile: filePath, encoding: .ascii)
|
||||
var machines: [Machine] = []
|
||||
var (aX, aY, bX, bY): (Int, Int, Int, Int) = (-1, -1, -1, -1)
|
||||
content.split(separator: "\n").forEach { line in
|
||||
if let m = line.wholeMatch(of: btnA) {
|
||||
aX = Int(m.output[1].substring!)!
|
||||
aY = Int(m.output[2].substring!)!
|
||||
} else if let m = line.wholeMatch(of: btnB) {
|
||||
bX = Int(m.output[1].substring!)!
|
||||
bY = Int(m.output[2].substring!)!
|
||||
} else if let m = line.wholeMatch(of: prize) {
|
||||
machines.append(Machine(aX: aX, aY: aY, bX: bX, bY: bY,
|
||||
przX: 10000000000000 + Int(m.output[1].substring!)!,
|
||||
przY: 10000000000000 + Int(m.output[2].substring!)!
|
||||
))
|
||||
}
|
||||
}
|
||||
return machines
|
||||
}
|
||||
|
||||
let machines = try readInput(CommandLine.arguments[1])
|
||||
var answer = 0
|
||||
machines.forEach { m in
|
||||
print(m)
|
||||
if let cost = m.solve() { answer += cost }
|
||||
}
|
||||
print(answer)
|
||||
|
Reference in New Issue
Block a user