summaryrefslogtreecommitdiffstats
path: root/day3/src/main.rs
blob: 8dffe3afaec1877d95d7df8de45cb89bae1016d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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);
  }
}