Skip to content

Commit

Permalink
add day 07
Browse files Browse the repository at this point in the history
  • Loading branch information
jan-may committed Dec 8, 2024
1 parent 5897513 commit db35588
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 1 deletion.
71 changes: 71 additions & 0 deletions y_2024/src/day_07.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use crate::lib::parse_input;

const INPUT_FILE: &str = "inputs/day_07.txt";
const P1_OPERATIONS: [&str; 2] = ["*", "+"];
const P2_OPERATIONS: [&str; 3] = ["*", "+", "||"];

/// Parses the input file into a list of targets and their associated values.
fn get_target_and_values() -> Vec<(i64, Vec<i64>)> {
parse_input(INPUT_FILE)
.iter()
.map(|line| {
let parts = line.split_whitespace().collect::<Vec<&str>>();
let target = parts[0].replace(':', "").parse::<i64>().unwrap();
let values = parts[1..]
.iter()
.map(|num| num.parse::<i64>().unwrap())
.collect();
(target, values)
})
.collect()
}

/// Evaluates a sequence of operations on a list of values from left to right.
fn evaluate(values: &[i64], operations: &[&str]) -> i64 {
let mut result = values[0];
for (i, operation) in operations.iter().enumerate() {
match *operation {
"*" => result *= values[i + 1],
"+" => result += values[i + 1],
"||" => {
let concatenated = format!("{}{}", result, values[i + 1])
.parse::<i64>()
.expect("Concatenation failed");
result = concatenated;
}
_ => panic!("Invalid operation"),
}
}
result
}

/// Solves the problem using the specified set of operations.
fn solve(operations: &[&str]) -> i64 {
let target_and_values = get_target_and_values();
let mut sum = 0;

for (target, values) in target_and_values {
let num_operations = values.len() - 1;
let all_combinations = (0..operations.len().pow(num_operations as u32)).map(|n| {
(0..num_operations)
.map(|i| operations[(n / operations.len().pow(i as u32)) % operations.len()])
.collect::<Vec<_>>()
});

for ops in all_combinations {
if evaluate(&values, &ops) == target {
sum += target;
break;
}
}
}
sum
}

pub fn part_1() -> i64 {
solve(&P1_OPERATIONS)
}

pub fn part_2() -> i64 {
solve(&P2_OPERATIONS)
}
4 changes: 3 additions & 1 deletion y_2024/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod day_03;
mod day_04;
mod day_05;
mod day_06;
mod day_07;
mod lib;

fn main() {
Expand All @@ -17,5 +18,6 @@ fn main() {
// println!("day 3: p1 {} | p2 {}", day_03::part_1(), day_03::part_2());
// println!("day 4: p1 {} | p2 {}", day_04::part_1(), day_04::part_2());
// println!("day 5: p1 {} | p2 {}", day_05::part_1(), 0);
println!("day 5: p1 {} | p2 {}", day_06::part_1(), day_06::part_2());
// println!("day 6: p1 {} | p2 {}", day_06::part_1(), day_06::part_2());
println!("day 7: p1 {} | p2 {}", day_07::part_1(), day_07::part_2());
}

0 comments on commit db35588

Please sign in to comment.