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
pub fn build_with_letters(given_letters: &[char], word: &str) -> bool {
let mut given_letters = given_letters.to_vec();
for letter in word.chars() {
if let Some(index) = given_letters.iter().position(|&x| x == letter) {
given_letters.remove(index);
} else {
return false;
}
}
true
}
pub fn search_for_words<'l, 'dict, D>(letters: &'l str, dictionary: D) -> Vec<(&'dict str, usize)>
where D: Iterator<Item = &'dict str>
{
let letters = letters.trim().chars().collect::<Vec<char>>();
let mut matches = dictionary.filter(|word| build_with_letters(&letters, word))
.map(|word| (word, word.chars().count()))
.collect::<Vec<(&str, usize)>>();
matches.sort_by(|a, b| b.1.cmp(&a.1));
matches
}
#[test]
fn find_trivial_word() {
let letters = "banana";
let words = vec!["banana"];
assert_eq!(search_for_words(letters, words.into_iter()),
vec![("banana", 6)]);
}
#[test]
fn find_in_order() {
let letters = "banana";
let words = vec!["banana", "ban"];
assert_eq!(search_for_words(letters, words.into_iter()),
vec![("banana", 6), ("ban", 3)]);
}