diff --git a/Cargo.lock b/Cargo.lock index 2bbdcb1..eb564c0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -37,6 +37,12 @@ version = "0.2.139" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79" +[[package]] +name = "once_cell" +version = "1.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" + [[package]] name = "parens" version = "0.1.0" @@ -81,6 +87,13 @@ dependencies = [ name = "repeated-groups" version = "0.1.0" +[[package]] +name = "scrabble" +version = "0.1.0" +dependencies = [ + "once_cell", +] + [[package]] name = "scramble" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 32c1b4c..032f738 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,5 +5,6 @@ members = [ "fraction-math", "parens", "repeated-groups", + "scrabble", "scramble" ] diff --git a/scrabble/Cargo.toml b/scrabble/Cargo.toml new file mode 100644 index 0000000..2f666cc --- /dev/null +++ b/scrabble/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "scrabble" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +once_cell = "1.17.1" diff --git a/scrabble/src/main.rs b/scrabble/src/main.rs new file mode 100644 index 0000000..0bb39eb --- /dev/null +++ b/scrabble/src/main.rs @@ -0,0 +1,67 @@ +use std::collections::HashMap; + +/// Given a string, calculate the score that it would get in a game of Scrabble. +/// For extra credit, try verifying if the string is a valid word, or take into +/// account premium squares! +/// +/// Scoring and example: +/// +/// 1 point: E, A, I, O, N, R, T, L, S, U +/// 2 points: D, G +/// 3 points: B, C, M, P +/// 4 points: F, H, V, W, Y +/// 5 points: K +/// 8 points: J, X +/// 10 points: Q, Z +/// +/// ``` +/// > scrabbleScore('FIZZBUZZ') +/// > 49 +/// ``` +use once_cell::sync::Lazy; + +static SCORE_TABLE: Lazy> = Lazy::new(|| { + let mut m = HashMap::new(); + m.insert('a', 1); + m.insert('b', 3); + m.insert('c', 3); + m.insert('d', 2); + m.insert('e', 1); + m.insert('f', 4); + m.insert('g', 2); + m.insert('h', 4); + m.insert('i', 1); + m.insert('j', 8); + m.insert('k', 5); + m.insert('l', 1); + m.insert('m', 3); + m.insert('n', 1); + m.insert('o', 1); + m.insert('p', 3); + m.insert('q', 10); + m.insert('r', 1); + m.insert('s', 1); + m.insert('t', 1); + m.insert('u', 1); + m.insert('v', 4); + m.insert('w', 4); + m.insert('x', 8); + m.insert('y', 4); + m.insert('z', 10); + + m +}); + +fn main() { + println!("{}", score_word("FIZZBUZZ".to_string())); +} + +fn score_word(s: String) -> usize { + let mut score = 0; + for c in s.chars() { + let mut c = c; + c.make_ascii_lowercase(); + score += *SCORE_TABLE.get(&c).unwrap_or(&0); + } + score +}