This commit is contained in:
2024-12-24 01:17:09 -08:00
parent b620dd9718
commit 6d0b1ab194
2 changed files with 30 additions and 20 deletions

View File

@@ -30,22 +30,15 @@ struct Circuit : CustomStringConvertible {
func readInput(_ filePath: String) throws -> Circuit {
let content = try String(contentsOfFile: filePath, encoding: .ascii)
let nodeRe = try Regex(#"([a-z0-9]+): (0|1)"#)
let gateRe = try Regex(#"([a-z0-9]+) (AND|OR|XOR) ([a-z0-9]+) -> ([a-z0-9]+)"#)
let opMap: [String: Op] = [
"AND": { $0 && $1 },
"OR": { $0 || $1 },
"XOR": { $0 != $1 }
]
var nodes: [String: Bool] = [:]
var gates: [Gate] = []
var endNodes: Set<String> = []
for line in content.split(separator: "\n") {
if let m = line.wholeMatch(of: nodeRe) {
let node = String(m.output[1].substring!)
let val = m.output[2].substring! == "1"
nodes[node] = val
}
if let m = line.wholeMatch(of: gateRe) {
let in1 = String(m.output[1].substring!)
let op = opMap[String(m.output[2].substring!)]!
@@ -57,16 +50,29 @@ func readInput(_ filePath: String) throws -> Circuit {
}
}
}
return Circuit(gates: gates, nodes: nodes, pendingEndNodes: endNodes)
return Circuit(gates: gates, nodes: [:], pendingEndNodes: endNodes)
}
extension Int {
func toNodes(_ prefix: String) -> [String: Bool] {
var nodes: [String: Bool] = [:]
for i in (0..<45) {
nodes[prefix + String(format: "%02d", i)] = ((self >> i) & 1) == 1
}
return nodes
}
}
var circuit = try readInput(CommandLine.arguments[1])
// generate random x y to try
let x = Int.random(in: 0..<(1<<45))
let y = Int.random(in: 0..<(1<<45))
circuit.nodes.merge(x.toNodes("x")) { l, r in l }
circuit.nodes.merge(y.toNodes("y")) { l, r in l }
// just print out the wrong bits for manual debugging. See input.dot
// print(circuit)
while true {
if let z = circuit.value(of: "z"),
let x = circuit.value(of: "x"),
let y = circuit.value(of: "y")
{
if let z = circuit.value(of: "z") {
print("x: " + String(x, radix: 2).reversed())
print("y: " + String(y, radix: 2).reversed())
let zStr = String(z, radix: 2).reversed()
@@ -82,3 +88,7 @@ while true {
circuit.run()
}
// use graphviz to render input.dot to svg
// run program to find out first bit that failed (highlighted in red)
// look at svg around that for irregularities (regular full adders are obvious)
// in this case z16 <-> fkb and z31 <-> rdn