This commit is contained in:
Christian
2023-12-06 19:13:15 +01:00
parent 6e60a3f2e6
commit 488b518f08
3 changed files with 276 additions and 83 deletions

67
src/bin/day04.rs Normal file
View File

@@ -0,0 +1,67 @@
use std::env;
use std::fs;
use std::collections::HashSet;
use anyhow::{Context, Result};
use regex::Regex;
fn main() -> Result<()> {
let filename = env::args()
.nth(1)
.context("./day04 <path to puzzle input>")?;
let input = fs::read_to_string(filename)?;
let re = Regex::new(r"\d+")?;
let lines = input.lines().collect::<Vec<_>>();
let mut count: Vec<usize> = vec![1; lines.len()];
let mut part1 = 0;
for (line_num, line) in lines.into_iter().enumerate() {
let mut hs = HashSet::new();
let (_, card_text) = line.split_once(':').unwrap();
let (winning, mine) = card_text.split_once('|').unwrap();
let winning_nums = re
.find_iter(winning)
.map(|m| m.as_str().parse::<u32>().unwrap());
let my_nums = re
.find_iter(mine)
.map(|m| m.as_str().parse::<u32>().unwrap());
for i in winning_nums {
hs.insert(i);
}
let mut num_matches: usize = 0;
for i in my_nums {
if hs.contains(&i) {
num_matches += 1;
}
}
for i in line_num + 1..line_num + num_matches + 1 {
if i >= count.len() {
break;
}
count[i] += count[line_num];
}
if num_matches > 0 {
part1 += 1 << (num_matches - 1);
}
}
let part2 = count.into_iter().sum::<usize>();
println!("1) {}", part1);
println!("2) {}", part2);
Ok(())
}