Files
advent-of-code-2023-rust/src/util.rs

103 lines
2.3 KiB
Rust

use std::fs;
use std::fmt::Display;
use num::Integer;
pub fn read_file(filename: &str) -> String {
return fs::read_to_string(filename)
.expect("Couldn't read file!");
}
pub fn into_lines(input: String) -> Vec<String> {
return input.lines().map(|l| l.to_owned()).collect();
}
#[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]
}
#[allow(dead_code)]
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, Hash)]
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))
}
}