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
////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2022 Scott MacDonald.
////////////////////////////////////////////////////////////////////////////////
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
const PANGRAM_SCORE_BOOST: i32 = 7;
const SCORE_MIN_LENGTH: usize = 5;
const WORD_MIN_LENGTH: usize = 4;

/// Holds details for a word that is considered an answer to the spelling bee
/// setup.
#[derive(Debug, PartialEq)]
pub struct Answer {
    pub word: String,
    pub score: i32,
    pub is_pangram: bool,
}

/// Finds all spelling bee answers from an iterable list of words.
pub fn find_all<I, S>(words: I, required: char, extra: &str) -> Vec<Answer>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    // IntoIterator inspiration from: https://stackoverflow.com/a/35626785
    let mut answers: Vec<Answer> = Vec::new();

    for w in words {
        match check_word(w.as_ref(), required, extra) {
            Some(ans) => answers.push(ans),
            None => {}
        };
    }

    answers
}

/// Test if the given word is a valid answer to the spelling bee, and return
/// scoring information if it is an answer. If the word is not an answer than
/// `None` will be returned.
///
/// # Notes
/// A word is considered an answer if it is at least four letters long, at least
/// one character matches `required`, and the remaining letters match of the
/// characters in `extra` or the required character. A pangram is when a
/// word's letters match both the required character, and every character listed
/// in `extra`.
///
/// Scoring is determined with the following rules:
///     1. Words of length four are worth one point.
///     2. Words longer than four letters are worth their length in points.
///     3. A pangram word gets an additional seven points.
///
/// # Examples
/// ```
/// use spellingbee::check_word;
/// assert!(check_word("loon", 'o', "unrlap").is_some());
/// assert!(check_word("unpopular", 'o', "unrlap").unwrap().is_pangram);
/// assert_eq!(7, check_word("pronoun", 'o', "unrlap").unwrap().score);
/// assert!(check_word("foobar", 'o', "unrlap").is_none());
/// ```
pub fn check_word(word: &str, required: char, extra: &str) -> Option<Answer> {
    // Words must be at least four characters.
    if word.len() < WORD_MIN_LENGTH {
        return None;
    }

    // Words must also contain the required character.
    if !word.contains(required) {
        return None;
    }

    // Words can only contain characters matching required or extra.
    if word
        .chars()
        .into_iter()
        .all(|x| x == required || extra.chars().any(|e| e == x))
    {
        // Count the number of unique letters that were matched. We do this with
        // a O(nm) algorithm to avoid allocating a hashmap since both n and m
        // are small.
        let mut uniq_count = 1; // The required char must always match.

        for e in extra.chars() {
            if word.chars().any(|w| w == e) {
                uniq_count += 1;
            }
        }

        let is_pangram = uniq_count == 1 + extra.len();

        // Scoring uses the following rules:
        //  1. Four letter words score 1 point.
        //  2. Five letter or longer words score their length in points.
        //  3. A pangram receives an extra 7 points.
        let mut score: i32 = 1;

        if word.len() >= SCORE_MIN_LENGTH {
            score = word.len() as i32;
        }

        if is_pangram {
            score += PANGRAM_SCORE_BOOST;
        }

        // Return answer as the word, its score and if it was a pangram.
        Some(Answer {
            word: word.to_string(),
            score,
            is_pangram,
        })
    } else {
        None
    }
}

#[cfg(test)]
#[allow(dead_code)]
mod tests {
    use crate::{check_word, find_all};

    #[test]
    fn empty_word_is_not_valid() {
        assert_eq!(None, check_word("", 'c', "ab"));
    }

    #[test]
    fn word_less_than_four_chars_not_valid() {
        assert_eq!(None, check_word("c", 'c', "ab"));
        assert_eq!(None, check_word("ca", 'c', "ab"));
        assert_eq!(None, check_word("cab", 'c', "ab"));

        assert_eq!(None, check_word("d", 'c', "ab"));
        assert_eq!(None, check_word("do", 'c', "ab"));
        assert_eq!(None, check_word("dog", 'c', "ab"));
    }

    #[test]
    fn word_uses_required_valid() {
        assert!(check_word("tttt", 't', "oe").is_some());
        assert!(check_word("tttttt", 't', "oe").is_some());
        assert!(check_word("ssss", 's', "oe").is_some());
    }

    #[test]
    fn word_missing_required_not_valid() {
        assert_eq!(None, check_word("oeoe", 't', "oe"));
        assert_eq!(None, check_word("oooo", 't', "oe"));
    }

    #[test]
    fn word_can_use_extra_chars() {
        assert!(check_word("tote", 't', "elom").is_some());
        assert!(check_word("totet", 't', "elom").is_some());
        assert!(check_word("mote", 't', "elom").is_some());
        assert!(check_word("molet", 't', "elom").is_some());
    }

    #[test]
    fn word_with_chars_not_in_required_or_extra_not_valid() {
        assert_eq!(None, check_word("dote", 't', "elom"));
        assert_eq!(None, check_word("note", 't', "elom"));
    }

    #[test]
    fn test_multiple_words() {
        let words = vec![
            "tote".to_string(),
            "vote".to_string(),
            "mote".to_string(),
            "soapy".to_string(),
        ];
        let answers = find_all(words.iter(), 't', "elom");
        assert_eq!(2, answers.len());
        assert_eq!("tote", answers[0].word);
        assert_eq!("mote", answers[1].word);
    }

    #[test]
    fn answer_contains_original_word() {
        assert_eq!("motel", check_word("motel", 't', "elom").unwrap().word);
        assert_eq!("tome", check_word("tome", 't', "elom").unwrap().word);
    }

    #[test]
    fn pangram_uses_all_letters() {
        assert_eq!(true, check_word("motel", 't', "elom").unwrap().is_pangram);
        assert_eq!(true, check_word("emotel", 't', "elom").unwrap().is_pangram);
        assert_eq!(false, check_word("motee", 't', "elom").unwrap().is_pangram);
        assert_eq!(false, check_word("mote", 't', "elom").unwrap().is_pangram);
    }

    #[test]
    fn four_length_score_is_one() {
        assert_eq!(1, check_word("tome", 't', "elom").unwrap().score);
        assert_eq!(1, check_word("tell", 't', "elom").unwrap().score);
    }

    #[test]
    fn score_equal_length_when_larger_than_four() {
        assert_eq!(5, check_word("motee", 't', "elom").unwrap().score);
        assert_eq!(5, check_word("tello", 't', "elom").unwrap().score);
        assert_eq!(6, check_word("tomtom", 't', "elom").unwrap().score);
        assert_eq!(9, check_word("tomtomtom", 't', "elom").unwrap().score);
    }

    #[test]
    fn pangram_adds_seven_to_score() {
        assert_eq!(12, check_word("motel", 't', "elom").unwrap().score);
        assert_eq!(13, check_word("emotel", 't', "elom").unwrap().score);
    }
}