lll_rs/vector/
bigvector.rs1use crate::vector::{Dot, Vector};
2
3use rug::Integer;
4
5use std::{
6 fmt,
7 ops::{Index, IndexMut},
8};
9
10#[derive(Clone)]
13pub struct BigVector {
14 coefficients: Vec<Integer>,
16
17 dimension: usize,
19}
20
21impl Vector for BigVector {
22 fn basis_vector(&self, position: usize) -> Self {
23 assert!(position < self.dimension);
24
25 let mut coefficients = vec![Integer::from(0); self.dimension()];
26 coefficients[position] = Integer::from(1);
27
28 Self {
29 coefficients,
30 dimension: self.dimension(),
31 }
32 }
33
34 fn init(dimension: usize) -> Self {
35 Self {
36 coefficients: vec![Default::default(); dimension],
37 dimension,
38 }
39 }
40
41 fn dimension(&self) -> usize {
42 self.dimension
43 }
44
45 fn add(&self, other: &Self) -> Self {
46 let n = self.dimension();
47
48 assert_eq!(n, other.dimension());
49
50 Self::from_vector(
51 (0..n)
52 .map(|i| Integer::from(&self.coefficients[i] + &other.coefficients[i]))
53 .collect(),
54 )
55 }
56
57 fn sub(&self, other: &Self) -> Self {
58 let n = self.dimension();
59
60 assert_eq!(n, other.dimension());
61
62 Self::from_vector(
63 (0..n)
64 .map(|i| Integer::from(&self.coefficients[i] - &other.coefficients[i]))
65 .collect(),
66 )
67 }
68}
69
70impl BigVector {
71 pub fn from_vector(coefficients: Vec<Integer>) -> Self {
73 Self {
74 dimension: coefficients.len(),
75 coefficients,
76 }
77 }
78
79 pub fn mulf(&self, other: &Integer) -> Self {
81 let n = self.dimension();
82
83 Self::from_vector(
84 (0..n)
85 .map(|i| Integer::from(&self.coefficients[i] * other))
86 .collect(),
87 )
88 }
89}
90
91impl Dot<Integer> for BigVector {
92 fn dot(&self, other: &Self) -> Integer {
93 let n = self.dimension();
94 assert_eq!(n, other.dimension());
95
96 (0..n)
97 .map(|i| Integer::from(&self.coefficients[i] * &other.coefficients[i]))
98 .sum()
99 }
100}
101
102impl Index<usize> for BigVector {
103 type Output = Integer;
104
105 fn index(&self, index: usize) -> &Integer {
106 &self.coefficients[index]
107 }
108}
109
110impl IndexMut<usize> for BigVector {
111 fn index_mut(&mut self, index: usize) -> &mut Integer {
112 &mut self.coefficients[index]
113 }
114}
115
116impl fmt::Debug for BigVector {
117 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
118 write!(f, "{:?}", self.coefficients)
119 }
120}