summaryrefslogtreecommitdiff
path: root/2024/07/rust
diff options
context:
space:
mode:
Diffstat (limited to '2024/07/rust')
-rw-r--r--2024/07/rust/Cargo.lock7
-rw-r--r--2024/07/rust/Cargo.toml6
-rw-r--r--2024/07/rust/src/main.rs55
3 files changed, 68 insertions, 0 deletions
diff --git a/2024/07/rust/Cargo.lock b/2024/07/rust/Cargo.lock
new file mode 100644
index 0000000..d1897ed
--- /dev/null
+++ b/2024/07/rust/Cargo.lock
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aoc_2024-07"
+version = "0.1.0"
diff --git a/2024/07/rust/Cargo.toml b/2024/07/rust/Cargo.toml
new file mode 100644
index 0000000..c64c1b5
--- /dev/null
+++ b/2024/07/rust/Cargo.toml
@@ -0,0 +1,6 @@
+[package]
+name = "aoc_2024-07"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
diff --git a/2024/07/rust/src/main.rs b/2024/07/rust/src/main.rs
new file mode 100644
index 0000000..07fef57
--- /dev/null
+++ b/2024/07/rust/src/main.rs
@@ -0,0 +1,55 @@
+use std::io;
+
+fn main() -> io::Result<()> {
+ let eqns = io::stdin()
+ .lines()
+ .flatten()
+ .collect::<Vec<_>>()
+ .iter()
+ .map(|line| line.split_once(": ").unwrap())
+ .map(|(ans, nums)| {
+ (
+ ans.parse::<u64>().unwrap(),
+ nums.split_whitespace()
+ .map(|s| s.parse::<u64>().unwrap())
+ .collect::<Vec<_>>(),
+ )
+ })
+ .collect::<Vec<_>>();
+
+ let silver: u64 = eqns
+ .iter()
+ .filter(|(ans, nums)| calibration(ans, nums, false))
+ .map(|(ans, _)| ans)
+ .sum();
+
+ let gold: u64 = eqns
+ .iter()
+ .filter(|(ans, nums)| calibration(ans, nums, true))
+ .map(|(ans, _)| ans)
+ .sum();
+
+ println!("silver: {silver}");
+ println!("gold: {gold}");
+
+ return Ok(());
+}
+
+fn concat(x: &u64, y: &u64) -> u64 {
+ x * (10u64.pow(y.ilog10() + 1)) + y
+}
+
+fn calibration(want: &u64, nums: &[u64], gold: bool) -> bool {
+ match nums {
+ [] => unreachable!(),
+ [x] => want == x,
+ [x, y, xs @ ..] => {
+ if x > want {
+ return false;
+ }
+ calibration(want, &[&[x + y], xs].concat(), gold) ||
+ calibration(want, &[&[x * y], xs].concat(), gold) ||
+ (gold && calibration(want, &[&[concat(x, y)], xs].concat(), gold) )
+ }
+ }
+}