Add day 4 rust
This commit is contained in:
parent
4dcc750416
commit
315b7c2d5e
2 changed files with 43 additions and 0 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -1,2 +1,3 @@
|
|||
*.in
|
||||
*.ex*
|
||||
day??
|
||||
|
|
42
day04.rs
Normal file
42
day04.rs
Normal file
|
@ -0,0 +1,42 @@
|
|||
use std::collections::HashSet;
|
||||
use std::io::{self, BufRead};
|
||||
|
||||
fn main() {
|
||||
// Part 1
|
||||
let mut part1 = 0;
|
||||
let cards: Vec<usize> = io::stdin()
|
||||
.lock()
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let line = line.unwrap();
|
||||
let (_, card) = line.split_once(": ").unwrap();
|
||||
let (winning, owned) = card.split_once(" | ").unwrap();
|
||||
|
||||
let winning: HashSet<i32> = winning
|
||||
.split_whitespace()
|
||||
.flat_map(str::parse)
|
||||
.collect();
|
||||
|
||||
let owned: HashSet<i32> = owned
|
||||
.split_whitespace()
|
||||
.flat_map(str::parse)
|
||||
.collect();
|
||||
|
||||
let count = winning.intersection(&owned).count();
|
||||
|
||||
part1 += 1 << (count - 1);
|
||||
count
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Part 2
|
||||
let mut dp = vec![1; cards.len()];
|
||||
let part2: i32 = (0..cards.len())
|
||||
.map(|i| {
|
||||
dp[i] += dp[i - cards[cards.len() - i - 1]..i].iter().sum::<i32>();
|
||||
dp[i]
|
||||
})
|
||||
.sum();
|
||||
|
||||
println!("{} {}", part1, part2);
|
||||
}
|
Loading…
Reference in a new issue