Day4 Rust

This commit is contained in:
dobiadi
2023-12-06 21:23:56 +01:00
parent 3335442a3f
commit 4f0e9d7c7c
4 changed files with 100 additions and 0 deletions

1
day4/rust/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
target

7
day4/rust/Cargo.lock generated Normal file
View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "rust"
version = "0.1.0"

8
day4/rust/Cargo.toml Normal file
View File

@@ -0,0 +1,8 @@
[package]
name = "rust"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

84
day4/rust/src/main.rs Normal file
View File

@@ -0,0 +1,84 @@
use std::collections::VecDeque;
struct Card {
_id: usize,
winning_numbers: Vec<usize>,
scratched_numbers: Vec<usize>,
}
fn main() {
let stdin = std::io::stdin();
let mut cards = Vec::new();
for line in stdin.lines() {
let line = line.unwrap();
let (card_id_str, numbers) = line.split_once(':').unwrap();
let card_id = card_id_str
.split_once(' ')
.unwrap()
.1
.trim()
.parse()
.unwrap();
let (winning_numbers_str, scratched_numbers_str) = numbers.split_once('|').unwrap();
let winning_numbers = winning_numbers_str
.split(' ')
.filter(|e| e.len() > 0)
.map(|e| e.parse().unwrap())
.collect();
let scratched_numbers = scratched_numbers_str
.split(' ')
.filter(|e| e.len() > 0)
.map(|e| e.parse().unwrap())
.collect();
cards.push(Card {
_id: card_id,
winning_numbers,
scratched_numbers,
});
}
let mut part1 = 0;
let mut part2 = 0;
let mut foresight = VecDeque::new();
for card in &cards {
let mut score = 0;
let mut win_num = 0;
let card_num = foresight.pop_front().unwrap_or(0) + 1;
part2 += card_num;
for scratched_number in &card.scratched_numbers {
if card.winning_numbers.contains(&scratched_number) {
win_num += 1;
if score == 0 {
score = 1;
} else {
score *= 2;
}
}
}
for i in 0..win_num {
if let Some(n) = foresight.get(i) {
foresight[i] = n + card_num;
} else {
foresight.push_back(card_num);
}
}
part1 += score;
}
println!("{}", part1);
println!("{}", part2);
}