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
use std::convert;
use std::f64::{MIN};
pub type Vector = Vec<f64>;
pub trait FPVector {
fn fmap<F>(&self, f: F) -> Vector where F: Fn(f64) -> f64;
fn reduce<F, T>(&self, init: T, f: F) -> f64
where F: Fn(f64, f64) -> f64,
T: convert::Into<f64>;
fn zip_with<F>(&self, f: F, other: &Vector) -> Vector
where F: Fn(f64, f64) -> f64;
}
impl FPVector for Vector {
fn fmap<F>(&self, f: F) -> Vector where F: Fn(f64) -> f64 {
self.clone().into_iter().map(|x| f(x)).collect::<Vector>()
}
fn reduce<F, T>(&self, init: T, f: F) -> f64
where F: Fn(f64, f64) -> f64,
T: convert::Into<f64> {
self.clone().into_iter().fold(
init.into(),
|x,y| f(x,y),
)
}
fn zip_with<F>(&self, f: F, other: &Vector) -> Vector
where F: Fn(f64, f64) -> f64 {
self.into_iter().zip(other).map(|(x,y)| f(*x,*y)).collect::<Vector>()
}
}
pub trait Algorithm {
fn rank(&self) -> Vec<usize>;
fn sign(&self) -> f64;
fn arg_max(&self) -> usize;
}
impl Algorithm for Vector {
fn rank(&self) -> Vec<usize> {
let l = self.len();
let idx = (1 .. (l+1)).map(|x| x as usize).collect::<Vec<usize>>();
let mut vec_tup = self.clone().into_iter().zip(idx.clone()).collect::<Vec<(f64, usize)>>();
vec_tup.sort_by(|x,y| x.0.partial_cmp(&y.0).unwrap().reverse());
let indices = vec_tup.into_iter().map(|(_,y)| y).collect::<Vec<usize>>();
idx.into_iter().map(|x| indices.clone().into_iter().position(|t| t == x).unwrap()).collect::<Vec<usize>>()
}
fn sign(&self) -> f64 {
let l = self.len();
let mut v = self.clone();
let mut sgn = 1f64;
for i in 0 .. (l-1) {
for j in 0 .. (l - 1 - i) {
if v[j] > v[j+1] {
sgn *= -1f64;
let (a, b) = (v[j], v[j+1]);
v[j] = b;
v[j+1] = a;
}
}
}
return sgn;
}
fn arg_max(&self) -> usize {
let v = self.clone();
let m = self.clone().into_iter().fold(MIN, |x,y| x.max(y));
v.into_iter().position(|x| x == m).unwrap()
}
}
pub trait VecOps {
type Scalar;
fn add(&self, other: &Self) -> Self;
fn sub(&self, other: &Self) -> Self;
fn mul(&self, other: &Self) -> Self;
fn div(&self, other: &Self) -> Self;
fn dot(&self, other: &Self) -> Self::Scalar;
}
impl VecOps for Vector {
type Scalar = f64;
fn add(&self, other: &Vector) -> Vector {
self.zip_with(|x, y| x + y, other)
}
fn sub(&self, other: &Vector) -> Vector {
self.zip_with(|x, y| x - y, other)
}
fn mul(&self, other: &Vector) -> Vector {
self.zip_with(|x, y| x * y, other)
}
fn div(&self, other: &Vector) -> Vector {
self.zip_with(|x, y| x / y, other)
}
fn dot(&self, other: &Vector) -> f64 {
self.mul(other).reduce(1, |x,y| x * y)
}
}