Introduction
Counting words is easy; counting every distinct word in a large file efficiently needs a proper data structure. This project implements a hash table with separate chaining and uses it to produce a frequency report.
Problem statement
Objectives
- Implement a hash table with chaining and the djb2 hash
- Process a file character by character
- Sort an array of pointers with qsort
- Free every allocation
Features
- Case-insensitive word counting (apostrophes kept)
- Line, sentence and character totals
- Longest word and average length
- Top-N frequency report with bars
- File name and N from the command line
Concepts demonstrated
- Hashing
- Linked lists
- Pointer arrays
- Character classification
System architecture
A 4093-bucket array of linked lists stores (word, count) entries; add_word hashes the word, walks the chain and either increments or prepends. After reading, all entries are collected into an array of pointers and sorted by count (then alphabetically) for the report.
Folder structure
Complete source code
Makefile
What each file does
- src/main.c
- The hash table (
hash,add_word,free_table), the character-level scanner and the report. - Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
Testing
./app sample.txt 6must matchtests/expected-output.txt.- Run it on a large file (a book from Project Gutenberg) and time it.
- Run on an empty file: it must report 0 words without crashing.
Common errors
"don't" counted as "don" and "t"
Apostrophes inside a word are kept; check the c == '\'' condition in the scanner.
Crash on very long "words"
Characters beyond MAX_WORD − 1 are ignored, protecting the buffer.
Possible improvements
- Ignore common stop words (the, a, is)
- Report word lengths as a histogram
- Process several files and compare them
Additional challenges
- 1Grow the hash table when the load factor exceeds 0.75.
- 2Find the most common two-word phrases (bigrams).
- 3Compute a readability score (Flesch reading ease).
Built and tested it yourself? Mark it to update your dashboard.