diff options
author | Justin Worthe <justin@worthe-it.co.za> | 2018-12-03 07:51:02 +0200 |
---|---|---|
committer | Justin Worthe <justin@worthe-it.co.za> | 2018-12-03 07:51:02 +0200 |
commit | 83485fffdd4034e91300bfa954bd68358181bc3a (patch) | |
tree | 45de7040d6be6cd26c2edf569b4e99d8aab96b4d /src/bin | |
parent | 4002dbfa903aae2ece66174bc28e7410768c084e (diff) |
Day 3: Finding collisions
Diffstat (limited to 'src/bin')
-rw-r--r-- | src/bin/day_3.rs | 60 |
1 files changed, 59 insertions, 1 deletions
diff --git a/src/bin/day_3.rs b/src/bin/day_3.rs index d15235a..685e288 100644 --- a/src/bin/day_3.rs +++ b/src/bin/day_3.rs @@ -1,18 +1,76 @@ extern crate advent_of_code_2018; use advent_of_code_2018::*; +use std::str::FromStr; + use std::error::Error; use std::path::PathBuf; +use std::collections::HashMap; + // cargo watch -cs "cargo run --release --bin day_3" +#[derive(Debug)] +struct Claim { + id: u32, + x: u32, + y: u32, + w: u32, + h: u32 +} + +impl FromStr for Claim { + type Err = Box<Error>; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + //#123 @ 3,2: 5x4 + let split = s + .split(|c: char| !c.is_numeric()) + .filter(|s| !s.is_empty()) + .map(|s| s.parse()) + .collect::<Result<Vec<u32>, _>>()?; + + Ok(Claim { + id: split[0], + x: split[1], + y: split[2], + w: split[3], + h: split[4] + }) + } +} + fn main() -> Result<(), Box<Error>> { let input = read_file(&PathBuf::from("inputs/3.txt"))?; + let claims = input.iter().map(|line| line.parse::<Claim>()).collect::<Result<Vec<_>, _>>()?; - println!("Input: {:?}", input); + let mut claimed = HashMap::new(); + for claim in &claims { + for x in claim.x..claim.x+claim.w { + for y in claim.y..claim.y+claim.h { + *claimed.entry((x,y)).or_insert(0) += 1; + } + } + } + let conflicts = claimed.values().filter(|&x| *x > 1).count(); + println!("Conflicts: {}", conflicts); + let conflict_free = claims.iter().filter(|c| check_for_conflicts(c, &claimed)).collect::<Vec<_>>(); + println!("Conflict free: {:?}", conflict_free); Ok(()) } + + +fn check_for_conflicts(claim: &Claim, claimed: &HashMap<(u32, u32), u32>) -> bool { + for x in claim.x..claim.x+claim.w { + for y in claim.y..claim.y+claim.h { + if claimed.get(&(x,y)).map_or(false, |c| *c > 1) { + return false; + } + } + } + true +} |