1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct Matrix<const R: usize, const C: usize>([[f32; C]; R]);

pub type SquareMatrix<const D: usize> = Matrix<D, D>;
pub type VecMatrix = Vec<Vec<f32>>;

#[macro_export]
macro_rules! matrix {
    () => (compile_error!("Empty matrix not allowed"));
    ($($($value:expr)*),*) => {
        Matrix::from([
            $([$($value),*],)*
        ])
    };
}

impl<const R: usize, const C: usize> Matrix<R, C> {
    pub fn new(closure: impl Fn(usize, usize) -> f32) -> Self {
        Self(std::array::from_fn(|row| {
            std::array::from_fn(|column| closure(row, column))
        }))
    }

    pub fn zero() -> Self {
        Self::new(|_, _| 0.0)
    }
    pub const fn is_square(&self) -> bool {
        R == C
    }

    pub fn rows(&self) -> [[f32; C]; R] {
        self.0
    }
    pub fn columns(&self) -> [[f32; R]; C] {
        std::array::from_fn(|i| self.rows().map(|row| row[i]))
    }

    pub fn transpose(&self) -> Matrix<C, R> {
        Matrix::from(self.columns())
    }

    pub fn map<F>(&self, f: F) -> Self
    where
        F: Fn(f32) -> f32,
    {
        Self::new(|r, c| f(self[r][c]))
    }

    pub fn merge<F>(&self, other: Matrix<R, C>, f: F) -> Self
    where
        F: Fn(f32, f32) -> f32,
    {
        Self::new(|r, c| f(self[r][c], other[r][c]))
    }
}

impl<const D: usize> SquareMatrix<D> {
    pub fn identity() -> Self {
        Self::new(|row, column| if row == column { 1.0 } else { 0.0 })
    }

    pub fn determinant(&self) -> f32 {
        Self::determinant_vec_impl(&self.into())
    }

    pub fn has_inverse(&self) -> bool {
        self.determinant() != 0.0
    }

    pub fn inverse(&self) -> Option<Self> {
        let det = self.determinant();
        if det == 0.0 {
            None
        } else {
            todo!()
        }
    }

    fn determinant_vec_impl(vec: &VecMatrix) -> f32 {
        let side_len = vec.len();
        match side_len {
            0 => 1.0,
            1 => vec[0][0],
            2 => (vec[0][0] * vec[1][1]) - (vec[0][1] * vec[1][0]),
            _ => {
                let mut det = 0.0;
                let main_row = &vec[0];
                for i in 0..vec.len() {
                    let to = side_len - 1;
                    let sub: VecMatrix = (0..to)
                        .map(|ri| {
                            (0..to)
                                .map(|ci| {
                                    let row = &vec[ri + 1];
                                    row[if ci >= i { ci + 1 } else { ci }]
                                })
                                .collect()
                        })
                        .collect();
                    det += (main_row[i] * Self::determinant_vec_impl(&sub))
                        * (if i % 2 == 0 { 1.0 } else { -1.0 })
                }
                det
            }
        }
    }
}

macro_rules! matrix_merge_op {
    ($type:path => $op:tt) => {
        impl<const R: usize, const C: usize> $type for Matrix<R, C> {
            type Output = Self;

            fn $op(self, rhs: Self) -> Self::Output {
                self.merge(rhs, |a, b| a.$op(b))
            }
        }
    };
}

matrix_merge_op!(std::ops::Add => add);
matrix_merge_op!(std::ops::Sub => sub);

impl<const R: usize, const C: usize, const C2: usize> std::ops::Mul<Matrix<C, C2>>
    for Matrix<R, C>
{
    type Output = Matrix<R, C2>;

    fn mul(self, other: Matrix<C, C2>) -> Self::Output {
        Matrix::new(|ri, ci| {
            let row = self.rows()[ri];
            let column = other.columns()[ci];
            let mut sum = 0.0;
            for i in 0..C {
                sum += row[i] * column[i];
            }
            sum
        })
    }
}

impl<const R: usize, const C: usize> std::ops::Mul<f32> for Matrix<R, C> {
    type Output = Self;
    fn mul(self, rhs: f32) -> Self::Output {
        self.map(|v| v * rhs)
    }
}

macro_rules! matrix_from_2d_num_array {
    ($($num:ty)*) => ($(
        impl<
            const R: usize,
            const C: usize
        > From<[[$num; C]; R]> for Matrix<R, C> {
            fn from(value: [[$num; C]; R]) -> Self {
                Self(value.map(|a| a.map(|b| b as f32)))
            }
        }
    )*)
}

matrix_from_2d_num_array!(f32 i32 usize);

impl<const R: usize, const C: usize> From<&Matrix<R, C>> for VecMatrix {
    fn from(val: &Matrix<R, C>) -> Self {
        val.rows().map(|r| r.to_vec()).to_vec()
    }
}

impl<const R: usize, const C: usize> Default for Matrix<R, C> {
    fn default() -> Self {
        Self::zero()
    }
}

impl<const R: usize, const C: usize> std::ops::Index<usize> for Matrix<R, C> {
    type Output = [f32; C];

    fn index(&self, row: usize) -> &Self::Output {
        &self.0[row]
    }
}

impl<const R: usize, const C: usize> std::fmt::Display for Matrix<R, C> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let lines = self.rows().map(|row| format!("{:?}", row));
        let longest = lines.iter().map(|s| s.len()).max().unwrap_or(0);
        writeln!(
            f,
            "{:^len$}",
            format!("({}x{} matrix)", R, C),
            len = longest
        )?;
        for line in lines {
            writeln!(f, "{line}")?;
        }
        Ok(())
    }
}