Files
advent_of_code_2021/december_5/src/main.rs
2021-12-06 23:17:49 +01:00

94 lines
2.7 KiB
Rust

use std::fs::File;
use std::io::{BufReader};
use std::io::prelude::*;
use std::vec;
fn main(){
let file = File::open("./input.txt").expect("Read failed");
let reader = BufReader::new(file);
let mut lines: Vec<((u32, u32),(u32, u32))> = Vec::new();
let mut max_val: u32 = 0;
let mut field: Vec<Vec<u32>> = Vec::new();
let mut danger_points = 0;
for line in reader.lines(){
let line_as_string = line.unwrap();
let split_string = line_as_string.split(" -> ").collect::<Vec<&str>>();
let origin = split_string[0].split(",").collect::<Vec<&str>>();
let dest = split_string[1].split(",").collect::<Vec<&str>>();
let x1 = origin[0].parse::<u32>().unwrap();
let y1 = origin[1].parse::<u32>().unwrap();
let x2 = dest[0].parse::<u32>().unwrap();
let y2 = dest[1].parse::<u32>().unwrap();
if origin.iter().max().unwrap().parse::<u32>().unwrap() > max_val {
max_val = origin.iter().max().unwrap().parse::<u32>().unwrap();
}
if dest.iter().max().unwrap().parse::<u32>().unwrap() > max_val {
max_val = dest.iter().max().unwrap().parse::<u32>().unwrap();
}
lines.push(((x1,y1),(x2,y2)))
}
max_val += 1;
for _ in 0..max_val {
field.push(vec![0; max_val as usize]);
}
for line in lines {
let x1 = (line.0).0 as usize;
let y1 = (line.0).1 as usize;
let x2 = (line.1).0 as usize;
let y2 = (line.1).1 as usize;
if x1 == x2 {
for y in y1.min(y2)..y2.max(y1)+1 {
field[y][x1] += 1;
}
} else if y1 == y2{
for x in x1.min(x2)..x2.max(x1)+1 {
field[y1][x] += 1;
}
} else {
let mut x_vec = Vec::new();
let mut y_vec = Vec::new();
for i in 0..(x1 as i32 - x2 as i32).abs() + 1 {
if x1 < x2 {
x_vec.push(x1 + i as usize);
} else {
x_vec.push(x1 - i as usize) ;
}
}
for i in 0..(y1 as i32 - y2 as i32).abs() + 1 {
if y1 < y2 {
y_vec.push(y1 + i as usize);
} else {
y_vec.push(y1 - i as usize) ;
}
}
let iter_len = (y1 as i32 - y2 as i32).abs() as usize;
for i in 0..iter_len + 1{
field[y_vec[i]][x_vec[i]] += 1;
}
}
}
for i in 0..max_val as usize{
for j in 0..max_val as usize {
if field[i][j] > 1 {
danger_points += 1;
}
}
}
println!("Dangerpoints: {}", danger_points);
}