2022 rust WIP matrix thing

This commit is contained in:
Maciej Jur 2022-12-10 01:16:56 +01:00
parent 1060e6b386
commit a187719d7d
2 changed files with 74 additions and 0 deletions

View file

@ -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) }

View 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
}
}