2022 rust WIP matrix thing
This commit is contained in:
parent
1060e6b386
commit
a187719d7d
|
@ -1,7 +1,10 @@
|
|||
pub mod matrix;
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::Path;
|
||||
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub enum Source { Scratch, Day(i32) }
|
||||
|
||||
|
|
71
2022/rust/src/utils/matrix.rs
Normal file
71
2022/rust/src/utils/matrix.rs
Normal file
|
@ -0,0 +1,71 @@
|
|||
#![allow(dead_code)]
|
||||
use std::ops::{Deref, Index, IndexMut};
|
||||
|
||||
|
||||
pub struct Matrix<T> {
|
||||
array: Vec<T>,
|
||||
rows: usize,
|
||||
cols: usize,
|
||||
}
|
||||
|
||||
impl<T: Default + Clone> Matrix<T> {
|
||||
pub fn new(rows: usize, cols: usize) -> Self {
|
||||
Self { rows, cols, array: vec![Default::default(); rows * cols] }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Matrix<T> {
|
||||
pub fn reshape(mut self, rows: usize, cols: usize) -> Matrix<T> {
|
||||
assert_eq!(self.rows * self.cols, rows * cols);
|
||||
self.rows = rows;
|
||||
self.cols = cols;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn get_at(&self, row: usize, col: usize) -> &T {
|
||||
let offset = self.get_offset(row, col);
|
||||
&self.array[offset]
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn get_mut_at(&mut self, row: usize, col: usize) -> &mut T {
|
||||
let offset = self.get_offset(row, col);
|
||||
&mut self.array[offset]
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn set_at(&mut self, row: usize, col: usize, value: T) {
|
||||
let offset = self.get_offset(row, col);
|
||||
self.array[offset] = value;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn get_offset(&self, row: usize, col: usize) -> usize {
|
||||
row * self.cols + col
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Index<usize> for Matrix<T> {
|
||||
type Output = T;
|
||||
|
||||
#[inline(always)]
|
||||
fn index(&self, index: usize) -> &Self::Output {
|
||||
&self.array[index]
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IndexMut<usize> for Matrix<T> {
|
||||
#[inline(always)]
|
||||
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
|
||||
&mut self.array[index]
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for Matrix<T> {
|
||||
type Target = Vec<T>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.array
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue