Created
December 7, 2024 11:39
-
-
Save weirddan455/5bfe8ca463337d7520412fba533b1640 to your computer and use it in GitHub Desktop.
Advent of Code Day 7 Part 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Equation { | |
result: u64, | |
ops: Box<[u64]> | |
} | |
fn parse_input() -> Vec<Equation> { | |
let mut eqs = Vec::new(); | |
for line in std::fs::read_to_string("input").unwrap().lines() { | |
let (r, o) = line.split_once(':').unwrap(); | |
let result: u64 = r.parse().unwrap(); | |
let ops: Box<[u64]> = o.split_whitespace().map(|s| s.parse::<u64>().unwrap()).collect(); | |
eqs.push(Equation{result, ops}); | |
} | |
eqs | |
} | |
fn combine(f: u64, s: u64) -> u64 { | |
let mut mul = 10; | |
let mut t = s; | |
loop { | |
t /= 10; | |
if t == 0 { | |
break; | |
} | |
mul *= 10; | |
} | |
f * mul + s | |
} | |
fn solve(result: u64, ops: &mut [u64]) -> bool { | |
if ops.len() == 1 { | |
return ops[0] == result; | |
} | |
let first = ops[0]; | |
let second = ops[1]; | |
ops[1] = first + second; | |
if solve(result, &mut ops[1..]) { | |
return true; | |
} | |
ops[1] = first * second; | |
if solve(result, &mut ops[1..]) { | |
return true; | |
} | |
ops[1] = combine(first, second); | |
if solve(result, &mut ops[1..]) { | |
return true; | |
} | |
ops[1] = second; | |
false | |
} | |
fn main() { | |
let input = parse_input(); | |
let mut answer = 0; | |
for mut i in input { | |
if solve(i.result, &mut i.ops) { | |
answer += i.result; | |
} | |
} | |
println!("Answer: {answer}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment