From df4a5a12d7303bb676b7dd4f5f0b0799b67dd140 Mon Sep 17 00:00:00 2001 From: StNicolay Date: Sat, 7 Dec 2024 10:47:17 +0300 Subject: [PATCH] Day 7 --- src/day6.rs | 2 ++ src/day7.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 5 +++-- 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 src/day7.rs diff --git a/src/day6.rs b/src/day6.rs index 7d66a31..399a3be 100644 --- a/src/day6.rs +++ b/src/day6.rs @@ -83,6 +83,7 @@ fn get_visited(board: &[Vec], mut pos: (usize, usize)) -> HashSet<(usi visited } +#[allow(dead_code)] pub fn task1() { let (board, pos) = parse_board(&std::fs::read_to_string("input.txt").unwrap()); let mut visited = get_visited(&board, pos); @@ -109,6 +110,7 @@ fn is_loop(board: &[Vec], mut pos: (usize, usize)) -> bool { } } +#[allow(dead_code)] pub fn task2() { let (mut board, pos) = parse_board(&std::fs::read_to_string("input.txt").unwrap()); let visited = get_visited(&board, pos); diff --git a/src/day7.rs b/src/day7.rs new file mode 100644 index 0000000..a65cd85 --- /dev/null +++ b/src/day7.rs @@ -0,0 +1,58 @@ +use crate::get_lines; + +use itertools::Itertools; + +#[derive(Clone, Copy)] +enum Operation { + Add, + Mul, + Concentration, +} + +impl Operation { + fn apply(self, a: u64, b: u64) -> u64 { + match self { + Self::Add => a + b, + Self::Mul => a * b, + Self::Concentration => { + let val = format!("{a}{b}"); + val.parse().unwrap() + } + } + } +} + +fn inner(ops: &[Operation]) { + let lines = get_lines("input.txt"); + let result: u64 = lines + .filter_map(|line| { + let (target, numbers) = line.split_once(": ").unwrap(); + let target: u64 = target.parse().unwrap(); + let numbers: Vec = numbers.split(' ').map(|num| num.parse().unwrap()).collect(); + let ops_set = (0..numbers.len() - 1) + .map(|_| ops.iter().copied()) + .multi_cartesian_product(); + for ops in ops_set { + let mut result = numbers[0]; + for (n, op) in numbers[1..].iter().zip(ops) { + result = op.apply(result, *n); + } + if result == target { + return Some(target); + } + } + None + }) + .sum(); + println!("{result}"); +} + +#[allow(dead_code)] +pub fn task1() { + inner(&[Operation::Add, Operation::Mul]); +} + +#[allow(dead_code)] +pub fn task2() { + inner(&[Operation::Add, Operation::Mul, Operation::Concentration]); +} diff --git a/src/main.rs b/src/main.rs index e989070..0e6ea05 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,7 @@ mod day3; mod day4; mod day5; mod day6; +mod day7; use std::{ fs::File, @@ -21,6 +22,6 @@ fn parse_line(line: &str, pattern: char) -> impl Iterator + '_ { } fn main() { - day6::task1(); - day6::task2(); + day7::task1(); + day7::task2(); }