day4 part1

This commit is contained in:
simon
2024-09-30 16:43:20 +02:00
parent cae09fba68
commit c0d1a77f5b
5 changed files with 1700 additions and 0 deletions

54
2023/day4/src/main.rs Normal file
View File

@@ -0,0 +1,54 @@
use std::fs;
use regex::Regex;
#[macro_use(c)]
extern crate cute;
fn main() {
/* battleplan
1. create a list for all the cards
1.1 parse input
1.1.1split on '|' and parse via regex both parts or whole thing via regex
1.2 build list
1.2.1 each value of the list represents a card
1.2.2 representation of a card = 2 lists, winning numbers, and drawn numbers
1.3 map the list to convert card info into the amount of points
1.4 sum the points*/
let content = fs::read_to_string("input").expect("Should have been able to read the file");
let lines_array = content.split("\n").collect::<Vec<_>>();
let number_regex = Regex::new(r"\d+").unwrap();
let mut all_cards: Vec<(Vec<i32>, Vec<i32>)> = Vec::new();
for line in lines_array {
if line == "" {
continue;
}
let winning_numbers_str = line.split("|").collect::<Vec<_>>()[0]
.split(":")
.collect::<Vec<_>>()[1];
let scratched_numbers_str = line.split("|").collect::<Vec<_>>()[1];
let card = (
c![n.as_str().parse::<i32>().unwrap(), for n in number_regex.find_iter(winning_numbers_str)],
c![n.as_str().parse::<i32>().unwrap(), for n in number_regex.find_iter(scratched_numbers_str)],
);
all_cards.push(card);
}
let part1_array: Vec<_> = all_cards
.iter()
.map(|x| {
x.0.clone()
.into_iter()
.filter(|y| x.1.contains(y))
.collect::<Vec<i32>>()
})
.into_iter()
.filter(|x| !x.is_empty())
.collect();
let part1: i32 = part1_array
.iter()
.map(|x| i32::pow(2, x.clone().len() as u32 -1))
.collect::<Vec<i32>>()
.iter()
.sum();
println!("Part 1: {part1}");
}