Advent of Code solutions
at main 75 lines 2.4 kB view raw
1use advent_core::{day_stuff, ex_for_day, Day}; 2 3pub struct Day7; 4 5impl Day for Day7 { 6 day_stuff!(7, "3749", "11387", Vec<(i64, Vec<i64>)>); 7 8 fn part_1(input: Self::Input) -> Option<String> { 9 let ans = input 10 .into_iter() 11 .filter_map(|(target, operands)| { 12 let ps: u64 = 1 << (operands.len() - 1); 13 for p in 0..=ps { 14 let res = operands.iter().enumerate().fold(0, |acc, (i, e)| { 15 if i == 0 { 16 acc + *e 17 } else if p & (1 << (i - 1)) != 0 { 18 acc * *e 19 } else { 20 acc + *e 21 } 22 }); 23 if res == target { 24 return Some(target); 25 } 26 } 27 None 28 }) 29 .sum::<i64>(); 30 31 Some(ans.to_string()) 32 } 33 34 fn part_2(input: Self::Input) -> Option<String> { 35 let ans = input 36 .into_iter() 37 .filter_map(|(target, operands)| { 38 let ps: u64 = 3_u64.pow((operands.len() - 1) as u32); 39 for p in 0..=ps { 40 let res = operands.iter().enumerate().fold(0, |acc, (i, e)| { 41 if i == 0 { 42 acc + *e 43 } else if p / 3_u64.pow((i - 1) as u32) % 3 == 1 { 44 acc * *e 45 } else if p / 3_u64.pow((i - 1) as u32) % 3 == 2 { 46 // Integer logartihm to prevent calls to to_string? 47 format!("{acc}{e}").parse().unwrap() 48 } else { 49 acc + *e 50 } 51 }); 52 if res == target { 53 return Some(target); 54 } 55 } 56 None 57 }) 58 .sum::<i64>(); 59 60 Some(ans.to_string()) 61 } 62 63 fn parse_input(input: &str) -> Self::Input { 64 input 65 .lines() 66 .map(|l| { 67 let (eq, rest) = l.split_once(": ").unwrap(); 68 ( 69 eq.parse().unwrap(), 70 rest.split(" ").map(|x| x.parse().unwrap()).collect(), 71 ) 72 }) 73 .collect() 74 } 75}