Files
contests/advent_of_code/2021/d4/src/main.rs

133 lines
3.3 KiB
Rust

use std::io::{self, BufRead};
use std::path::Path;
use std::fs::File;
use std::collections::HashMap;
use text_io::scan;
// -- PART 1 --
// We playin bingo now
// Input is first a sequence of integers
// Followed by a number of bingo cards
// Goal is to find the bingo card that has bingo first and calculate some metrics of it
// Metrics are the last called number multiplied by sum of all numbers that were not needed for bingo
#[derive(Debug,PartialEq)]
struct Card {
numbers : HashMap<u64, (usize, usize)>,
opens : [[bool; 5]; 5],
score : u64,
}
impl Card {
fn new() -> Card {
Card { numbers: HashMap::new(), opens: [[true; 5]; 5], score: 0 }
}
fn call(&mut self, n: u64) -> Option<u64> {
let search_result = self.numbers.get(&n);
match search_result {
None => return None,
Some(&coords) => return self.take(n, coords),
}
}
fn take(&mut self, n: u64, (x, y): (usize, usize)) -> Option<u64> {
self.score -= n;
self.opens[x][y] = false;
match self.check((x, y)) {
false => return None,
true => return Some(self.score),
}
}
fn check(&self, (x, y): (usize, usize)) -> bool {
let mut result_x = true;
let mut result_y = true;
for b in self.opens[x] {
if b {
result_x = false;
}
}
for i in 0..self.opens.len() {
if self.opens[i][y] {
result_y = false;
}
}
return result_x || result_y;
}
fn insert(&mut self, n: u64, coords: (usize, usize)) -> () {
self.numbers.insert(n, coords);
self.score += n;
}
}
fn main(){
println!("Advent of Code #4!\n");
let path = Path::new("./4.txt");
let display = path.display();
let file = match File::open(&path) {
Err(why) => panic!("Couldn't open {}: {}", display, why),
Ok(file) => file,
};
let mut lines = io::BufReader::new(file).lines();
let mut numbers = Vec::<u32>::new();
let mut bingo_cards = Vec::<Card>::new();
// let mut c = Card::new();
// c.insert(1, (0, 1));
// c.insert(2, (1, 1));
// c.insert(3, (2, 1));
// c.insert(4, (3, 1));
// c.insert(5, (4, 1));
// assert_eq!(c.call(1), None);
// assert_eq!(c.call(2), None);
// assert_eq!(c.call(3), None);
// assert_eq!(c.call(4), None);
// assert_eq!(c.call(5), Some(0));
let first_line = lines.nth(0).unwrap().unwrap();
let mut acc: u32 = 0;
for c in first_line.chars() {
if c != ',' && c != '\n' {
acc *= 10;
acc += c.to_digit(10).unwrap();
} else{
numbers.push(acc);
acc = 0;
}
}
let mut n_start = 2;
let mut bingo_start_line = lines.nth(n_start);
while !bingo_start_line.is_none() {
let card = Card::new();
for i in 0..5 {
let cur_line = lines.nth(n_start + i).unwrap().unwrap();
let a: i32;
let b: i32;
let c: i32;
let d: i32;
let e: i32;
scan!(cur_line.bytes() => "{} {} {} {} {}", a, b, c, d, e);
println!("{} {} {} {} {}", a, b, c, d, e);
}
n_start += 6;
bingo_start_line = lines.nth(n_start);
}
}