add scrabble solver

main
William Perron 1 year ago
parent 02423a5d92
commit e4660ab365
No known key found for this signature in database
GPG Key ID: D1815C43C9BA3DE1

13
Cargo.lock generated

@ -37,6 +37,12 @@ version = "0.2.139"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79" checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79"
[[package]]
name = "once_cell"
version = "1.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
[[package]] [[package]]
name = "parens" name = "parens"
version = "0.1.0" version = "0.1.0"
@ -81,6 +87,13 @@ dependencies = [
name = "repeated-groups" name = "repeated-groups"
version = "0.1.0" version = "0.1.0"
[[package]]
name = "scrabble"
version = "0.1.0"
dependencies = [
"once_cell",
]
[[package]] [[package]]
name = "scramble" name = "scramble"
version = "0.1.0" version = "0.1.0"

@ -5,5 +5,6 @@ members = [
"fraction-math", "fraction-math",
"parens", "parens",
"repeated-groups", "repeated-groups",
"scrabble",
"scramble" "scramble"
] ]

@ -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"

@ -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<HashMap<char, usize>> = 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
}
Loading…
Cancel
Save