forked from basvanwesting/genetic-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpermutate_scrabble.rs
363 lines (332 loc) · 12 KB
/
permutate_scrabble.rs
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
use genetic_algorithm::strategy::permutate::prelude::*;
use num::{BigUint, ToPrimitive};
use std::collections::{HashMap, HashSet};
type Row = usize;
type Column = usize;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Orientation {
Horizontal,
Vertical,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WordPosition(pub Row, pub Column, pub Orientation);
impl Allele for WordPosition {}
#[derive(Clone, Debug)]
struct ScrabbleFitness {
pub words: Vec<&'static str>,
pub rows: usize,
pub columns: usize,
pub row_scores: Vec<isize>,
pub column_scores: Vec<isize>,
pub debug: bool,
position_map: HashMap<(usize, usize), Vec<(usize, char)>>,
related_word_ids: HashMap<usize, HashSet<usize>>,
letter_board: Vec<Vec<char>>,
}
impl Fitness for ScrabbleFitness {
type Genotype = MultiListGenotype<WordPosition>;
fn calculate_for_chromosome(
&mut self,
chromosome: &FitnessChromosome<Self>,
_genotype: &FitnessGenotype<Self>,
) -> Option<FitnessValue> {
let mut score: isize = 0;
self.position_map
.iter_mut()
.for_each(|(_, vec)| vec.clear());
self.related_word_ids
.iter_mut()
.for_each(|(_, set)| set.clear());
chromosome
.genes
.iter()
.enumerate()
.for_each(|(index, value)| {
let word = self.words[index];
match *value {
WordPosition(row, column, Orientation::Horizontal) => {
word.chars().enumerate().for_each(|(char_index, char)| {
self.position_map
.get_mut(&(row, column + char_index))
.unwrap()
.push((index, char));
})
}
WordPosition(row, column, Orientation::Vertical) => {
word.chars().enumerate().for_each(|(char_index, char)| {
self.position_map
.get_mut(&(row + char_index, column))
.unwrap()
.push((index, char));
})
}
}
});
// position score
for ((row, column), position_data) in &self.position_map {
match position_data.as_slice() {
[] => {
self.letter_board[*row][*column] = ' ';
}
[(_index, char)] => {
self.letter_board[*row][*column] = *char;
score += self.row_scores[*row] + self.column_scores[*column];
}
[(first_index, first_char), (second_index, second_char)] => {
if *first_char == *second_char {
self.letter_board[*row][*column] = *first_char;
score += 3 * self.row_scores[*row] + 3 * self.column_scores[*column];
self.related_word_ids
.get_mut(first_index)
.unwrap()
.insert(*second_index);
self.related_word_ids
.get_mut(second_index)
.unwrap()
.insert(*first_index);
} else {
self.letter_board[*row][*column] = '?';
score -= (self.rows * self.columns) as isize;
if self.debug {
println!(
"conflicting char: ({}, {}), at: ({}, {})",
*first_char, *second_char, *row, *column
);
}
}
}
rest => {
self.letter_board[*row][*column] = '?';
score -= (self.rows * self.columns * rest.len()) as isize;
if self.debug {
println!("conflicting multiple chars at: ({}, {})", *row, *column);
}
}
}
}
let mut touching_word_ids: HashSet<usize> = HashSet::with_capacity(self.words.len());
let starting_set = self
.related_word_ids
.values()
.max_by_key(|set| set.len())
.unwrap();
ScrabbleFitness::recursive_touching_sets(
starting_set,
&self.related_word_ids,
&mut touching_word_ids,
);
self.words.iter().enumerate().for_each(|(index, word)| {
if !touching_word_ids.contains(&index) {
score -= (self.rows * self.columns * word.len()) as isize;
if self.debug {
println!("word not touching main group: {}", word);
}
}
});
(0..self.rows).for_each(|row| {
String::from_iter(self.letter_board[row].iter())
.split_ascii_whitespace()
.filter(|str| str.len() > 1)
.for_each(|str| {
let known = self
.words
.iter()
.find(|word| word.eq_ignore_ascii_case(str));
if known.is_none() {
score -= (self.rows * self.columns * str.len()) as isize;
if self.debug {
println!("invalid horizontal string: {}", str);
}
}
});
});
(0..self.columns).for_each(|column| {
String::from_iter((0..self.rows).map(|row| self.letter_board[row][column]))
.split_ascii_whitespace()
.filter(|str| str.len() > 1)
.for_each(|str| {
let known = self
.words
.iter()
.find(|word| word.eq_ignore_ascii_case(str));
if known.is_none() {
score -= (self.rows * self.columns * str.len()) as isize;
if self.debug {
println!("invalid vertical string: {}", str);
}
}
});
});
Some(score)
}
}
impl ScrabbleFitness {
pub fn new(
words: Vec<&'static str>,
rows: usize,
columns: usize,
row_scores: Vec<isize>,
column_scores: Vec<isize>,
debug: bool,
) -> Self {
let mut position_map = HashMap::with_capacity(rows * columns);
for row in 0..rows {
for column in 0..columns {
position_map.insert((row, column), Vec::with_capacity(words.len()));
}
}
let mut related_word_ids: HashMap<usize, HashSet<usize>> =
HashMap::with_capacity(words.len());
for index in 0..words.len() {
related_word_ids.insert(index, HashSet::with_capacity(words.len()));
}
let letter_board: Vec<Vec<char>> = vec![vec![' '; columns]; rows];
Self {
words,
rows,
columns,
row_scores,
column_scores,
debug,
position_map,
related_word_ids,
letter_board,
}
}
pub fn recursive_touching_sets(
set: &HashSet<usize>,
data: &HashMap<usize, HashSet<usize>>,
acc: &mut HashSet<usize>,
) {
set.iter().for_each(|index| {
if acc.insert(*index) {
if let Some(next_set) = data.get(index) {
ScrabbleFitness::recursive_touching_sets(next_set, data, acc);
}
}
})
}
}
#[derive(Clone)]
pub struct CustomReporter(usize);
impl StrategyReporter for CustomReporter {
type Genotype = MultiListGenotype<WordPosition>;
fn on_new_generation<S: StrategyState<Self::Genotype>, C: StrategyConfig>(
&mut self,
genotype: &Self::Genotype,
state: &S,
_config: &C,
) {
if state.current_generation() % self.0 == 0 {
let progress = (BigUint::from(state.current_generation() * 100)
/ &genotype.chromosome_permutations_size())
.to_u8();
println!(
"progress: {}, current_generation: {}, best_generation: {}",
progress.map_or("-".to_string(), |v| format!("{:3.3}%", v)),
state.current_generation(),
state.best_generation(),
);
}
}
fn on_new_best_chromosome<S: StrategyState<Self::Genotype>, C: StrategyConfig>(
&mut self,
_genotype: &Self::Genotype,
state: &S,
_config: &C,
) {
println!(
"new best - current_generation: {}, best_fitness_score: {:?}",
state.current_generation(),
state.best_fitness_score(),
);
}
}
fn main() {
env_logger::init();
let rows = 5;
let columns = 5;
let row_scores: Vec<isize> = (0..rows)
.rev()
.zip(0..rows)
.map(|(v1, v2)| (v1.min(v2) + 1) as isize)
.collect();
let column_scores: Vec<isize> = (0..columns)
.rev()
.zip(0..columns)
.map(|(v1, v2)| (v1.min(v2) + 1) as isize)
.collect();
println!("{:?}", row_scores);
println!("{:?}", column_scores);
//let words: Vec<&'static str> = vec!["ada", "aad", "bas"];
let words: Vec<&'static str> = vec!["bean", "glee", "edge", "light", "note"];
let mut allele_lists: Vec<Vec<WordPosition>> = vec![vec![]; words.len()];
words.iter().enumerate().for_each(|(index, word)| {
for row in 0..rows {
for column in 0..=(columns - word.len()) {
allele_lists[index].push(WordPosition(row, column, Orientation::Horizontal));
}
}
for row in 0..=(rows - word.len()) {
for column in 0..columns {
allele_lists[index].push(WordPosition(row, column, Orientation::Vertical));
}
}
});
let genotype = MultiListGenotype::builder()
.with_allele_lists(allele_lists)
.build()
.unwrap();
println!("{}", genotype);
let mut permutate = Permutate::builder()
.with_genotype(genotype)
.with_fitness(ScrabbleFitness::new(
words.clone(),
rows,
columns,
row_scores.clone(),
column_scores.clone(),
false,
))
.with_par_fitness(true)
// .with_reporter(PermutateReporterSimple::new(100_000))
.with_reporter(CustomReporter(100_000))
.build()
.unwrap();
if false {
let guard = pprof::ProfilerGuardBuilder::default()
.frequency(1000)
.blocklist(&["libc", "libgcc", "pthread", "vdso"])
.build()
.unwrap();
permutate.call();
if let Ok(report) = guard.report().build() {
let file = std::fs::File::create("flamegraph_scrabble.svg").unwrap();
report.flamegraph(file).unwrap();
};
} else {
permutate.call();
}
println!("{}", permutate);
if let Some(best_chromosome) = permutate.best_chromosome() {
let mut fitness = ScrabbleFitness::new(
words.clone(),
rows,
columns,
row_scores.clone(),
column_scores.clone(),
true,
);
fitness.calculate_for_chromosome(&best_chromosome, &permutate.genotype);
fitness.letter_board.iter().for_each(|columns| {
let string = String::from_iter(columns.iter());
println!("{}", string.replace(' ', "."));
});
println!(
"Valid solution with fitness score: {:?}",
best_chromosome.fitness_score()
);
} else {
println!("Invalid solution with fitness score: None");
}
}