advent-of-code/src/2023/04-scratchcards/part_one.rs

55 lines
1.3 KiB
Rust

use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
use std::collections::HashSet;
pub fn part_one() {
if let Ok(lines) = read_lines("./input.txt") {
let mut result = 0;
for line in lines {
result += process_line(&line.unwrap());
}
println!("{}", result);
}
}
fn process_line(s: &str) -> u32 {
let mut winning_numbers = HashSet::new();
let mut res = 0;
let nums_str: Vec<&str> = s.split(':').collect::<Vec<&str>>()[1].split('|').collect();
let w_str = nums_str[0].trim().split_whitespace().collect::<Vec<&str>>();
let w_nums: Vec<u32> = w_str.iter().map(|s| s.parse::<u32>().unwrap()).collect();
for n in w_nums {
winning_numbers.insert(n);
}
let b_str = nums_str[1].trim().split_whitespace().collect::<Vec<&str>>();
let b_nums: Vec<u32> = b_str.iter().map(|s| s.parse::<u32>().unwrap()).collect();
for n in b_nums {
if winning_numbers.contains(&n) {
if res == 0 {
res = 1;
} else {
res *= 2;
}
}
}
return res;
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}