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
use std::ops::Neg;

use num_traits::{One};

use crate::SquareMatrix;

use super::matrix_init;
use super::minor::Minor;

pub trait Adj: SquareMatrix
where
    Self::Output: SquareMatrix
{
    type Output;

    /// Returns the adjugate matrix of the given square matrix
    /// 
    /// adj(A)
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// let a = [
    ///     [1.0, 2.0],
    ///     [3.0, 4.0]
    /// ];
    /// let aa = [
    ///     [4.0, -2.0],
    ///     [-3.0, 1.0]
    /// ];
    /// assert_eq!(a.adj(), aa);
    /// ```
    fn adj(&self) -> Self::Output;
}

impl<F: One> Adj for [[F; 1]; 1]
where
    Self: SquareMatrix
{
    type Output = Self;

    fn adj(&self) -> Self::Output
    {
        [[F::one()]]
    }
}

impl<F: Neg<Output = F> + Copy> Adj for [[F; 2]; 2]
where
    Self: SquareMatrix
{
    type Output = Self;

    fn adj(&self) -> Self::Output
    {
        [
            [self[1][1], -self[0][1]],
            [-self[1][0], self[0][0]]
        ]
    }
}

macro_rules! adj {
    ($i:expr) => {
        impl<F: One + Neg<Output = F>> Adj for [[F; $i]; $i]
        where
            Self: SquareMatrix + Minor<Output = F, Index = (usize, usize)>
        {
            type Output = Self;
        
            fn adj(&self) -> Self::Output
            {
                matrix_init(|r, c| if (r+c)%2 == 0 {F::one()} else {-F::one()}*self.minor((c, r)))
            }
        }
    };
}

adj!(3);
adj!(4);
adj!(5);
adj!(6);
adj!(7);
adj!(8);
adj!(9);
adj!(10);
adj!(11);
adj!(12);
adj!(13);
adj!(14);
adj!(15);
adj!(16);