Day 4 cleanup
This commit is contained in:
@@ -4,7 +4,6 @@ use std::fs;
|
|||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use regex::Regex;
|
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
let filename = env::args()
|
let filename = env::args()
|
||||||
@@ -12,50 +11,33 @@ fn main() -> Result<()> {
|
|||||||
.context("./day04 <path to puzzle input>")?;
|
.context("./day04 <path to puzzle input>")?;
|
||||||
let input = fs::read_to_string(filename)?;
|
let input = fs::read_to_string(filename)?;
|
||||||
|
|
||||||
let re = Regex::new(r"\d+")?;
|
|
||||||
|
|
||||||
let lines = input.lines().collect::<Vec<_>>();
|
let lines = input.lines().collect::<Vec<_>>();
|
||||||
|
|
||||||
let mut count: Vec<usize> = vec![1; lines.len()];
|
let mut count: Vec<usize> = vec![1; lines.len()];
|
||||||
|
|
||||||
let mut part1 = 0;
|
let mut part1 = 0;
|
||||||
for (line_num, line) in lines.into_iter().enumerate() {
|
for (line_num, line) in lines.into_iter().enumerate() {
|
||||||
let mut hs = HashSet::new();
|
|
||||||
|
|
||||||
let (_, card_text) = line.split_once(':').unwrap();
|
let (_, card_text) = line.split_once(':').unwrap();
|
||||||
let (winning, mine) = card_text.split_once('|').unwrap();
|
let (winning_str, mine_str) = card_text.split_once('|').unwrap();
|
||||||
|
|
||||||
let winning_nums = re
|
let winning = winning_str
|
||||||
.find_iter(winning)
|
.split_ascii_whitespace()
|
||||||
.map(|m| m.as_str().parse::<u32>().unwrap());
|
.map(|m| m.parse::<i32>().unwrap())
|
||||||
|
.collect::<HashSet<_>>();
|
||||||
|
|
||||||
let my_nums = re
|
let mine = mine_str
|
||||||
.find_iter(mine)
|
.split_ascii_whitespace()
|
||||||
.map(|m| m.as_str().parse::<u32>().unwrap());
|
.map(|m| m.parse::<i32>().unwrap());
|
||||||
|
|
||||||
for i in winning_nums {
|
let num_matches = mine.filter(|n| winning.contains(n)).count();
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
for i in (line_num + 1)..(line_num + num_matches + 1).min(count.len()) {
|
||||||
count[i] += count[line_num];
|
count[i] += count[line_num];
|
||||||
}
|
}
|
||||||
|
|
||||||
if num_matches > 0 {
|
if num_matches > 0 {
|
||||||
part1 += 1 << (num_matches - 1);
|
part1 += 1 << (num_matches - 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let part2 = count.into_iter().sum::<usize>();
|
let part2 = count.into_iter().sum::<usize>();
|
||||||
|
|||||||
Reference in New Issue
Block a user