summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorReiner Herrmann <reiner@reiner-h.de>2024-12-07 21:16:46 +0100
committerReiner Herrmann <reiner@reiner-h.de>2024-12-07 21:16:46 +0100
commit65dfc7c940d6fe1d1fa29648e21107a32f5f7e16 (patch)
treec56973781bd3b1dfbbe84838d7a40ed5be365bac
parentc82296633a0fa896d0c05415f2ee8f6d62b29150 (diff)
day7 solution 2
-rw-r--r--src/bin/day7.rs27
1 files changed, 20 insertions, 7 deletions
diff --git a/src/bin/day7.rs b/src/bin/day7.rs
index 60b08b1..934e0d9 100644
--- a/src/bin/day7.rs
+++ b/src/bin/day7.rs
@@ -2,26 +2,38 @@ static DAY: u8 = 7;
fn main() {
let input = advent::read_lines(DAY);
- println!("{DAY}a: {}", calibration_result(&input));
- println!("{DAY}b: {}", 0);
+ println!("{DAY}a: {}", calibration_result(&input, false));
+ println!("{DAY}b: {}", calibration_result(&input, true));
}
-fn calculateable(result: i64, operands: &[i64]) -> bool {
+fn calculateable(result: i64, operands: &[i64], with_concat: bool) -> bool {
if operands.len() == 1 {
return result == operands[0];
}
let rem = &operands[..=operands.len()-2];
let op = operands[operands.len()-1];
- calculateable(result - op, rem) || (result % op == 0 && calculateable(result / op, rem))
+ if with_concat {
+ let result_str = result.to_string();
+ let op_str = op.to_string();
+ if result_str.ends_with(&op_str) && result_str.len() > op_str.len() {
+ let result_str = result_str.chars().take(result_str.len() - op_str.len()).collect::<String>();
+ let result = result_str.parse::<i64>().unwrap();
+ if calculateable(result, rem, with_concat) {
+ return true;
+ }
+ }
+ }
+ ((result - op >= 0) && calculateable(result - op, rem, with_concat))
+ || (result % op == 0 && calculateable(result / op, rem, with_concat))
}
-fn calibration_result(input: &[String]) -> i64 {
+fn calibration_result(input: &[String], with_concat: bool) -> i64 {
let mut sum = 0;
for line in input {
let (result, operands) = line.split_once(": ").unwrap();
let result = result.parse::<i64>().unwrap();
let operands = operands.split(" ").map(|x| x.parse::<i64>().unwrap()).collect::<Vec<_>>();
- if calculateable(result, &operands) {
+ if calculateable(result, &operands, with_concat) {
sum += result;
}
}
@@ -45,6 +57,7 @@ mod tests {
"21037: 9 7 18 13",
"292: 11 6 16 20",
].iter().map(|&x| String::from(x)).collect::<Vec<_>>();
- assert_eq!(calibration_result(&input), 3749);
+ assert_eq!(calibration_result(&input, false), 3749);
+ assert_eq!(calibration_result(&input, true), 11387);
}
}