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
#![doc = include_str!("../README.md")]
#[derive(Debug)]
pub struct Characters {
pub names: Vec<&'static str>,
pub costs: Vec<usize>,
}
macro_rules! load_csv {
($path:tt) => {
{
let mut characters: Vec<&str> = Vec::new();
let costs: Vec<usize> = include_str!(
$path
).lines().enumerate().filter_map( |(line_index, line_value)| {
if line_index != 0 {
Some(
line_value.split(',').map( |comma_value| {
comma_value.parse::<usize>().unwrap()
}).collect::<Vec<usize>>()
)
} else {
characters = line_value.split(',').collect();
None
}
}).into_iter().flatten().collect();
Characters { names: characters, costs: costs }
}
};
}
#[derive(Debug)]
pub struct Database {
pub characters: Characters,
pub max_distance_size: usize
}
impl Database {
pub fn new() -> Database {
return Database {
characters: load_csv!("./../docs/assets/csv/characters.csv"),
max_distance_size: 255
};
}
pub fn get_distance(&self, from: &str, to: &str) -> u8 {
let index_x = match self.characters.names.iter().position(|&r| r == from) {
Some(i) => i,
None => return self.max_distance_size as u8
};
let index_y = match self.characters.names.iter().position(|&r| r == to) {
Some(i) => i,
None => return self.max_distance_size as u8
};
return match self.characters.costs[index_y + ( index_x * self.characters.names.len() )] {
i if self.max_distance_size < i => { self.max_distance_size as u8 },
i => i as u8,
};
}
pub fn get_word_distance(&self, str1: &str, str2: &str) -> usize {
let table_x_size = str1.chars().count() + 1;
let table_y_size = str2.chars().count() + 1;
let mut table = vec![0; table_x_size * table_y_size];
for i in 0..table_x_size {
table[i] = i * self.max_distance_size;
}
for i in 0..table_y_size {
table[i*(table_x_size)] = i * self.max_distance_size;
}
for i in 1..table_y_size {
for j in 1..table_x_size {
let up = table[j+((i-1)*table_x_size) ] + self.max_distance_size;
let left = table[j+( i *table_x_size)-1] + self.max_distance_size;
let upper_left = {
let char1 = str1.chars().nth(j-1).unwrap();
let char2 = str2.chars().nth(i-1).unwrap();
let c = if char1 == char2 { 0 } else { self.get_distance( &char1.to_string(), &char2.to_string() ) as usize };
table[j+((i-1)*table_x_size)-1] + c
};
table[j+(i*table_x_size)] = std::cmp::min(std::cmp::min(up, left), upper_left);
}
}
return table[(table_x_size*table_y_size)-1 as usize];
}
}
pub fn new() -> Database {
return Database::new();
}
pub mod search;