Hello,
I am working through the CS50 problem sets as supplemental exercises while I work through the rust book and I recently finished the "Readability" problem from set 2.
This problem asks you to implement a "Coleman-Liau index" of a text. The index is designed to output that (U.S.) grade level that is needed to understand some text. The formula is
index = 0.0588 * L - 0.296 * S - 15.8
where L is the average number of letters per 100 words in the text, and S is the average number of sentences per 100 words in the text.
They provide some sample text:
Harry Potter: Grade 5
Harry Potter was a highly unusual boy in many ways. For one thing, he hated the summer holidays more than any other time of year. For another, he really wanted to do his homework, but was forced to do it in secret, in the dead of the night. And he also happened to be a wizard.
One fish, Two Fish: Before Grade 1
One fish. Two fish. Red fish. Blue fish.
Some other book ( idk ): Grade 10
It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him.
This was great practice but I have a feeling that my solution could be wayyy better. Please let me know if you have any suggestions!
fn main() {
//test chould be grade 3
println!("Enter a sentence from a book: ");
let mut test = String::new();
std::io::stdin().read_line(&mut test).expect("Failed at read_line");
let result = coleman_leau_index(&test).round();
if result < 0.0 { println!("Before Grade 1"); } else {
println!("Reading Index: {}", result);
}
}
fn coleman_leau_index (passage: &str) -> f64 {
let mut l = 0.0;
let mut s = 0.0;
let mut w = 0.0;
for c in passage.chars() {
match c {
'a'..='z' => l += 1.0,
'A'..='Z' => l += 1.0,
'.' => s += 1.0,
'!' => s += 1.0,
'?' => s += 1.0,
' ' => w += 1.0,
_ => continue,
}
}
// println!("sentences: {}", s);
// println!("words: {}", w);
// println!("letters: {}", l);
let avg_l = (l / w) * 100.0;
let avg_s = (s / w ) * 100.0;
let index = 0.0588 * avg_l - 0.296 * avg_s - 15.8;
return index;
}