diff options
| author | Jan Tuomi <jan.tuomi@eficode.com> | 2018-12-05 18:12:49 +0200 |
|---|---|---|
| committer | Jan Tuomi <jan.tuomi@eficode.com> | 2018-12-05 18:12:49 +0200 |
| commit | 544047037c431cabcd224dc9a5451f4794ed5234 (patch) | |
| tree | 30f5cc431c7581fbb45975d3f799be72b28ef99f /day3/src/main.rs | |
| parent | 257ce22cd4bc5b561feea9a6e19415a86c250e23 (diff) | |
Solve day3
Diffstat (limited to 'day3/src/main.rs')
| -rw-r--r-- | day3/src/main.rs | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/day3/src/main.rs b/day3/src/main.rs new file mode 100644 index 0000000..8dffe3a --- /dev/null +++ b/day3/src/main.rs @@ -0,0 +1,87 @@ +use std::env; +use std::io::BufReader; +use std::io::BufRead; +use std::fs::File; +use std::process; + +#[macro_use] extern crate text_io; + +struct Claim { + _id: u32, + x: u32, + y: u32, + width: u32, + height: u32 +} + +fn main() { + let args: Vec<String> = env::args().collect(); + if args.len() != 2 { + println!("Wrong number of arguments. Provide just a file name."); + process::exit(1); + } + let filename = &args[1]; + println!("Using file {} as input.", filename); + let f = match File::open(filename) { + Ok(file) => file, + Err(e) => { + println!("Failed to open file {}. {:?}", filename, e); + process::exit(1); + } + }; + let file = BufReader::new(&f); + let mut claims: Vec<Claim> = Vec::new(); + let mut max_width = 0; + let mut max_height = 0; + // exercise 1 + for line in file.lines() { + let l = line.unwrap(); + let (id, x, y, width, height): (u32, u32, u32, u32, u32); + scan!(l.bytes() => "#{} @ {},{}: {}x{}", id, x, y, width, height); + if x + width > max_width { + max_width = x + width; + } + if y + height > max_height { + max_height = y + height; + } + let claim = Claim { _id: id, x, y, width, height }; + claims.push(claim); + } + + let (w, h) = (max_width as usize, max_height as usize); + let mut grid: Vec<Vec<u32>> = vec![vec![0; w]; h]; + + for claim in &claims { + for j in claim.y..(claim.y + claim.height) { + for i in claim.x..(claim.x + claim.width) { + let (x, y) = (i as usize, j as usize); + grid[y][x] += 1; + } + } + } + + let mut result = 0; + for j in 0..max_height as usize { + for i in 0..max_width as usize { + if grid[j][i] >= 2 { + result += 1; + } + } + } + + println!("Result: {}", result); + + // exercise 2 + 'claims: for claim in &claims { + for j in claim.y..(claim.y + claim.height) { + for i in claim.x..(claim.x + claim.width) { + let (x, y) = (i as usize, j as usize); + if grid[y][x] > 1 { + continue 'claims; + } + } + } + + println!("Disjoint claim: {}", claim._id); + } +} |
