[WIP] Day 1
This commit is contained in:
103
src/util.rs
Normal file
103
src/util.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
use std::fs;
|
||||
use std::fmt::Display;
|
||||
|
||||
use num::Integer;
|
||||
|
||||
pub fn read_file(filename: &str) -> Vec<String> {
|
||||
|
||||
let contents = fs::read_to_string(filename)
|
||||
.expect("Couldn't read file!");
|
||||
|
||||
let mut res: Vec<String> = Vec::new();
|
||||
contents.lines().for_each(|l| res.push(String::from(l)));
|
||||
|
||||
res
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Grid<T> {
|
||||
pub(crate) width: usize,
|
||||
pub(crate) data: Vec<T>
|
||||
}
|
||||
|
||||
impl<T: Clone + Sized> Grid<T> {
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn set_row(&mut self, y: usize, v: T) {
|
||||
// let range = &mut self.data[x * self.width..(x+1) * self.width];
|
||||
for i in self.width * y..self.width * (y + 1) {
|
||||
self.data[i] = v.to_owned();
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn set_col(&mut self, x: usize, v: T) {
|
||||
for y in 0..self.height() {
|
||||
let idx = self.idx(&x, &y);
|
||||
self.data[idx] = v.to_owned();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn idx(&self, x: &usize, y: &usize) -> usize {
|
||||
y * self.width + x
|
||||
}
|
||||
|
||||
pub(crate) fn height(&self) -> usize {
|
||||
self.data.len() / self.width
|
||||
}
|
||||
|
||||
pub(crate) fn get(&self, x: &usize, y: &usize) -> &T {
|
||||
let idx = self.idx(x, y);
|
||||
&self.data[idx]
|
||||
}
|
||||
|
||||
pub fn set(&mut self, x: &usize, y: &usize, v: T) {
|
||||
let idx = self.idx(x, y);
|
||||
self.data[idx] = v;
|
||||
}
|
||||
}
|
||||
|
||||
impl <T: Display + Clone + Sized> Grid<T> {
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn print(&self) {
|
||||
|
||||
self.print_range(0, self.width, 0, self.height());
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn print_range(&self, from_x: usize, to_x: usize, from_y: usize, to_y: usize) {
|
||||
|
||||
for y in from_y.max(0)..to_y.min(self.height()) {
|
||||
for x in from_x.max(0)..to_x.min(self.width) {
|
||||
print!("{}", self.get(&x, &y))
|
||||
}
|
||||
println!();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Coord<T> where T: Sized {
|
||||
pub x: T,
|
||||
pub y: T
|
||||
}
|
||||
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl<T> Coord<T> where T: Sized {
|
||||
pub(crate) fn new(x: T, y: T) -> Self {
|
||||
Coord { x, y }
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl <T> Coord<T> where T: Integer + Copy {
|
||||
pub fn manhattan_dist(&self, other: &Coord<T>) -> T {
|
||||
self.x.max(other.x).sub(self.x.min(other.x)) + self.y.max(other.y).sub(self.y.min(other.y))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user