Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@
- [`HashMap`](std-types/hashmap.md)
- [Exercise: Counter](std-types/exercise.md)
- [Solution](std-types/solution.md)
- [Exercise: Word Counter](std-types/word_counter.md)
- [Solution](std-types/word_counter_solution.md)
- [Standard Library Traits](std-traits.md)
- [Comparisons](std-traits/comparisons.md)
- [Operators](std-traits/operators.md)
Expand Down
7 changes: 7 additions & 0 deletions src/std-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
clap = { version = "4.4", features = ["derive"] }

[[bin]]
name = "hashset"
path = "exercise.rs"

[[bin]]
name = "word_counter"
path = "word_counter.rs"
Binary file added src/std-types/word_counter.exe
Copy link
Collaborator

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!

Binary file not shown.
93 changes: 93 additions & 0 deletions src/std-types/word_counter.md
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:
Copy link
Collaborator

Choose a reason for hiding this comment

The 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)
Copy link
Collaborator

Choose a reason for hiding this comment

The 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
Copy link
Collaborator

Choose a reason for hiding this comment

The 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);
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing closing triple-backtick

Binary file added src/std-types/word_counter.pdb
Copy link
Collaborator

Choose a reason for hiding this comment

The 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?)

Binary file not shown.
140 changes: 140 additions & 0 deletions src/std-types/word_counter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// ANCHOR: word_counter
use std::collections::HashMap;
use clap::Parser;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't talk about clap in fundamentals. And, command-line interface is sort of out-of-scope for this exercise, anyway -- the assignment relates to counting words, and the segment is about types in std. This should probably just take a static string as input.


/// 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();
}
Loading