From f685f51b09d29adaa509f126375d3049c4846d20 Mon Sep 17 00:00:00 2001 From: Erin Date: Mon, 4 Dec 2023 23:03:07 +0100 Subject: [PATCH] Day 04 Part 1 --- src/bin/day03.rs | 10 ++++++---- src/bin/day04.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) create mode 100644 src/bin/day04.rs diff --git a/src/bin/day03.rs b/src/bin/day03.rs index e3dfb05..1eb4150 100644 --- a/src/bin/day03.rs +++ b/src/bin/day03.rs @@ -1,8 +1,10 @@ -use color_eyre::{ - eyre::{bail, ensure}, - Result, +use { + color_eyre::{ + eyre::{bail, ensure}, + Result, + }, + std::{cell::Cell, collections::HashMap, io::stdin, rc::Rc}, }; -use std::{cell::Cell, collections::HashMap, io::stdin, rc::Rc}; #[derive(Clone, Copy)] struct SliceCols<'a, T> { diff --git a/src/bin/day04.rs b/src/bin/day04.rs new file mode 100644 index 0000000..b94a991 --- /dev/null +++ b/src/bin/day04.rs @@ -0,0 +1,36 @@ +use {color_eyre::eyre::ContextCompat, color_eyre::Result, std::io::stdin}; + +fn main() -> Result<()> { + Ok(println!( + "{}", + stdin() + .lines() + .map(|ln| -> Result<_> { + let ln = ln?; + let (winning, nums) = ln + .split_once(':') + .context("Invalid record: missing ':' separator")? + .1 + .split_once('|') + .context("Invalid record: missing '|' separator")?; + + let winning = winning + .split_whitespace() + .map(str::parse) + .collect::, _>>()?; + + let n = nums + .split_whitespace() + .map(str::parse) + .map(|item| item.map(|item| winning.contains(&item))) + .try_fold::<_, _, Result<_>>(0, |acc, x| Ok(acc + x? as u64))?; + + if n != 0 { + Ok(2_u64.pow(u32::try_from(n)?.saturating_sub(1))) + } else { + Ok(0) + } + }) + .try_fold::<_, _, Result<_>>(0, |acc, x| Ok(acc + x?))? + )) +}