mirror of
https://github.com/RussellChamp/advent-of-code-2024-rust.git
synced 2026-10-27 23:52:29 +00:00
day 7 pt1
This commit is contained in:
1 parent
30b9e9e249
commit
9cacd9db7e
2 files changed
+85
No files matched your search
@@ -0,0 +1,9 @@
|
||||
190: 10 19
|
||||
3267: 81 40 27
|
||||
83: 17 5
|
||||
156: 15 6
|
||||
7290: 6 8 6 15
|
||||
161011: 16 10 13
|
||||
192: 17 8 14
|
||||
21037: 9 7 18 13
|
||||
292: 11 6 16 20
|
||||
@@ -0,0 +1,76 @@
|
||||
advent_of_code::solution!(7);
|
||||
|
||||
pub fn part_one(input: &str) -> Option<usize> {
|
||||
let total: usize = input.lines().filter_map(|line| {
|
||||
// println!("{line}");
|
||||
let m: Vec<&str> = line.split(": ").collect();
|
||||
let total = m[0].parse::<usize>().unwrap();
|
||||
let values: Vec<usize> = m[1].split(' ').map(|v| v.parse::<usize>().unwrap()).collect();
|
||||
|
||||
// println!("LINE: {} = {:?}", total, values);
|
||||
|
||||
if can_calc(total, values) { Some(total) } else { None }
|
||||
// Some(total)
|
||||
}).sum();
|
||||
// println!("TOTAL: {}", total);
|
||||
|
||||
return Some(total);
|
||||
}
|
||||
|
||||
pub fn part_two(input: &str) -> Option<u32> {
|
||||
None
|
||||
}
|
||||
|
||||
// allowed operators: + and *
|
||||
// all possible options OP^(values count - 1)
|
||||
// eg 190: 10 19 -- has TWO possible paths, 10 + 19 and 10 * 19
|
||||
// eg 123: 4 5 6 3 -- has 8 possible paths; 4+5+6+3, 4+5+6*3, ... 4*5*6*3
|
||||
|
||||
fn can_calc(total: usize, values: Vec<usize>) -> bool {
|
||||
let is_valid = values.into_iter().fold(vec![0 as usize], |subtotals, next_value| {
|
||||
process(&subtotals, next_value)
|
||||
}).iter().any(|t| *t == total);
|
||||
|
||||
is_valid
|
||||
}
|
||||
|
||||
fn process(sum: &Vec<usize>, next_value: usize) -> Vec<usize> {
|
||||
sum.into_iter().flat_map(|v| {
|
||||
vec![v + next_value, v * next_value]
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_process() {
|
||||
let sum: Vec<u32> = vec![1];
|
||||
let next_value = 10;
|
||||
|
||||
let result = process(&sum, next_value);
|
||||
assert_eq!(result, vec![11, 10]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_can_calc() {
|
||||
let values: Vec<u32> = vec![1,2,3,4];
|
||||
let total: u32 = 10;
|
||||
|
||||
let result = can_calc(total, values);
|
||||
assert_eq!(result, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_part_one() {
|
||||
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
|
||||
assert_eq!(result, Some(3749));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_part_two() {
|
||||
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
|
||||
assert_eq!(result, None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user