-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Add Word Counter Exercise with Solution #2717
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
--- | ||
minutes: 20 | ||
--- | ||
|
||
# Exercise: Word Counter | ||
|
||
Create a program that counts the frequency of words in a given text. The program should: | ||
|
||
1. Take a string of text as input | ||
2. Split the text into words (consider words to be separated by whitespace) | ||
3. Count how many times each word appears (case-insensitive) | ||
4. Print the words and their counts in alphabetical order | ||
|
||
Use a `HashMap` to store the word counts. | ||
|
||
## Example | ||
|
||
```rust | ||
fn main() { | ||
let text = "the quick brown fox jumps over the lazy dog"; | ||
let counts = count_words(text); | ||
print_word_counts(&counts); | ||
} | ||
``` | ||
|
||
Expected output: | ||
``` | ||
brown: 1 | ||
dog: 1 | ||
fox: 1 | ||
jumps: 1 | ||
lazy: 1 | ||
over: 1 | ||
quick: 1 | ||
the: 2 | ||
``` | ||
|
||
## Tasks | ||
|
||
1. Implement the `count_words` function that takes a string slice and returns a `HashMap<String, u32>` | ||
2. Make the word counting case-insensitive (e.g., "The" and "the" count as the same word) | ||
3. Implement the `print_word_counts` function that prints the word counts in alphabetical order | ||
4. Add tests for: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We haven't talked about testing yet. Most exercises focus on getting the task solved, rather than testing. |
||
- Empty input | ||
- Simple text with repeated words | ||
- Case-insensitive counting | ||
|
||
## Extension Tasks (Optional) | ||
|
||
1. Add support for reading text from a file | ||
2. Add statistics like total words, unique words, and average word length | ||
3. Find and display the most common words | ||
|
||
[View solution](word_counter_solution.md) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We typically don't include a link, since it is just the next slide. |
||
|
||
```rust,editable | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should use anchors to include the non-solution parts of the code. |
||
use std::collections::HashMap; | ||
|
||
/// WordCounter counts the frequency of words in text. | ||
struct WordCounter { | ||
word_counts: HashMap<String, usize>, | ||
} | ||
|
||
impl WordCounter { | ||
/// Create a new WordCounter. | ||
fn new() -> Self { | ||
todo!("Initialize the WordCounter") | ||
} | ||
|
||
/// Count words in the given text. | ||
fn count_words(&mut self, text: &str) { | ||
todo!("Implement word counting logic") | ||
} | ||
|
||
/// Get the count for a specific word. | ||
fn word_count(&self, word: &str) -> usize { | ||
todo!("Return the count for the given word") | ||
} | ||
|
||
/// Find the most frequent word(s) and their count. | ||
fn most_frequent(&self) -> Vec<(&str, usize)> { | ||
todo!("Find and return the most frequent word(s)") | ||
} | ||
} | ||
|
||
#[test] | ||
fn test_word_counter() { | ||
let mut counter = WordCounter::new(); | ||
counter.count_words("Hello world, hello Rust!"); | ||
assert_eq!(counter.word_count("hello"), 2); | ||
assert_eq!(counter.word_count("rust"), 1); | ||
assert_eq!(counter.word_count("world"), 1); | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Missing closing triple-backtick |
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This file should not be included (I'm not even sure what creates it?) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,140 @@ | ||
// ANCHOR: word_counter | ||
use std::collections::HashMap; | ||
use clap::Parser; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We don't talk about |
||
|
||
/// A word counting program | ||
#[derive(Parser)] | ||
#[command(author, version, about, long_about = None)] | ||
struct Args { | ||
/// Text to count words in | ||
#[arg(short, long)] | ||
text: Option<String>, | ||
|
||
/// File to read text from | ||
#[arg(short, long)] | ||
file: Option<String>, | ||
|
||
/// Ignore case when counting words | ||
#[arg(short, long, default_value_t = true)] | ||
ignore_case: bool, | ||
} | ||
|
||
/// WordCounter counts the frequency of words in text. | ||
struct WordCounter { | ||
word_counts: HashMap<String, usize>, | ||
ignore_case: bool, | ||
} | ||
|
||
impl WordCounter { | ||
/// Create a new WordCounter. | ||
fn new(ignore_case: bool) -> Self { | ||
WordCounter { | ||
word_counts: HashMap::new(), | ||
ignore_case, | ||
} | ||
} | ||
|
||
/// Count words in the given text. | ||
fn count_words(&mut self, text: &str) { | ||
for word in text.split_whitespace() { | ||
let word = if self.ignore_case { | ||
word.to_lowercase() | ||
} else { | ||
word.to_string() | ||
}; | ||
*self.word_counts.entry(word).or_insert(0) += 1; | ||
} | ||
} | ||
|
||
/// Get the count for a specific word. | ||
fn word_count(&self, word: &str) -> usize { | ||
let word = if self.ignore_case { | ||
word.to_lowercase() | ||
} else { | ||
word.to_string() | ||
}; | ||
self.word_counts.get(&word).copied().unwrap_or(0) | ||
} | ||
|
||
/// Find the most frequent word(s) and their count. | ||
fn most_frequent(&self) -> Vec<(&str, usize)> { | ||
if self.word_counts.is_empty() { | ||
return Vec::new(); | ||
} | ||
|
||
let max_count = self.word_counts.values().max().unwrap(); | ||
self.word_counts | ||
.iter() | ||
.filter(|(_, &count)| count == *max_count) | ||
.map(|(word, &count)| (word.as_str(), count)) | ||
.collect() | ||
} | ||
|
||
/// Print word counts in alphabetical order | ||
fn print_counts(&self) { | ||
let mut words: Vec<_> = self.word_counts.keys().collect(); | ||
words.sort(); | ||
for word in words { | ||
println!("{}: {}", word, self.word_counts[word]); | ||
} | ||
} | ||
} | ||
// ANCHOR_END: word_counter | ||
|
||
// ANCHOR: tests | ||
#[test] | ||
fn test_empty_counter() { | ||
let counter = WordCounter::new(true); | ||
assert_eq!(counter.word_count("any"), 0); | ||
assert!(counter.most_frequent().is_empty()); | ||
} | ||
|
||
#[test] | ||
fn test_simple_text() { | ||
let mut counter = WordCounter::new(true); | ||
counter.count_words("Hello world, hello Rust!"); | ||
assert_eq!(counter.word_count("hello"), 2); | ||
assert_eq!(counter.word_count("rust"), 1); | ||
assert_eq!(counter.word_count("world"), 1); | ||
} | ||
|
||
#[test] | ||
fn test_case_insensitive() { | ||
let mut counter = WordCounter::new(true); | ||
counter.count_words("Hello HELLO hello"); | ||
assert_eq!(counter.word_count("hello"), 3); | ||
assert_eq!(counter.word_count("HELLO"), 3); | ||
} | ||
|
||
#[test] | ||
fn test_most_frequent() { | ||
let mut counter = WordCounter::new(true); | ||
counter.count_words("hello world hello rust hello"); | ||
let most_frequent = counter.most_frequent(); | ||
assert_eq!(most_frequent, vec![("hello", 3)]); | ||
} | ||
// ANCHOR_END: tests | ||
|
||
fn main() { | ||
let args = Args::parse(); | ||
|
||
let mut counter = WordCounter::new(args.ignore_case); | ||
|
||
if let Some(text) = args.text { | ||
counter.count_words(&text); | ||
} else if let Some(file) = args.file { | ||
match std::fs::read_to_string(file) { | ||
Ok(content) => counter.count_words(&content), | ||
Err(e) => { | ||
eprintln!("Error reading file: {}", e); | ||
std::process::exit(1); | ||
} | ||
} | ||
} else { | ||
eprintln!("Please provide either --text or --file"); | ||
std::process::exit(1); | ||
} | ||
|
||
println!("Word counts:"); | ||
counter.print_counts(); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Definitely do not check in the windows executable!