programming
haiku
poetry
algorithm
creative-writing

How would you write a program to generate Haiku?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

A haiku generator is a good programming problem because it combines hard constraints with creative variation. The program has to satisfy the classic 5-7-5 syllable structure, but it also needs enough vocabulary and selection rules to avoid producing meaningless word soup.

Start with the Structure

For a simple English-language generator, the core rule is the three-line syllable pattern:

  • line one has 5 syllables
  • line two has 7 syllables
  • line three has 5 syllables

That means the real foundation is syllable counting. If the program cannot estimate syllables reliably, it cannot produce believable haiku no matter how good the randomization is.

Organize Words by Syllable Count

One practical starting point is to keep a dictionary of words grouped by syllable count. Then the generator builds a line by selecting words whose counts add up to the target.

python
1import random
2
3WORDS = {
4    1: ["wind", "pond", "rain", "moss", "moon"],
5    2: ["river", "silent", "petal", "autumn"],
6    3: ["butterfly", "harmony", "morning dew"],
7}
8
9
10def build_line(target_syllables: int) -> str:
11    remaining = target_syllables
12    chosen = []
13
14    while remaining > 0:
15        valid_counts = [count for count in WORDS if count <= remaining]
16        syllables = random.choice(valid_counts)
17        chosen.append(random.choice(WORDS[syllables]))
18        remaining -= syllables
19
20    return " ".join(chosen)
21
22
23def generate_haiku() -> str:
24    return "\n".join([
25        build_line(5),
26        build_line(7),
27        build_line(5),
28    ])
29
30
31print(generate_haiku())

This version is small, readable, and already respects the syllable pattern exactly.

Improve Quality with Themes

Pure randomness often produces lines that are technically valid but semantically weak. A common improvement is to group words by theme, such as rain, winter, or spring, and choose all three lines from the same vocabulary set.

python
1import random
2
3THEMES = {
4    "spring": {
5        1: ["buds", "rain", "light"],
6        2: ["blossom", "sparrow", "meadow"],
7        3: ["butterfly", "morning dew"],
8    }
9}
10
11
12def build_themed_line(theme: str, target_syllables: int) -> str:
13    remaining = target_syllables
14    chosen = []
15    word_bank = THEMES[theme]
16
17    while remaining > 0:
18        valid_counts = [count for count in word_bank if count <= remaining]
19        syllables = random.choice(valid_counts)
20        chosen.append(random.choice(word_bank[syllables]))
21        remaining -= syllables
22
23    return " ".join(chosen)

Even a small themed dictionary usually sounds better than one large unrelated pool of words.

Use Templates for Grammar

Syllables alone do not guarantee that the result reads like language. A good next step is to introduce templates, such as noun-verb-noun or adjective-noun-verb. The generator then chooses words not just by syllable count but also by role.

This reduces grammatical chaos and makes the output feel more intentional. It is still a generator, not a human poet, but the structure becomes noticeably stronger.

Backtracking Helps When Choices Get Tighter

If the vocabulary is small, a greedy random choice can paint itself into a corner. For example, a line may have one syllable left and no one-syllable words that fit the selected template. A recursive backtracking approach solves that problem by trying one word, exploring the remainder, and stepping back when the line cannot be completed.

That technique is especially useful once you add grammar templates or part-of-speech constraints.

Syllable Counting Is the Hard Part

For a toy generator, a hand-curated dictionary is enough. For a larger generator, syllable counting becomes the hardest problem because English pronunciation is irregular. A pronunciation dictionary or syllable-estimation library is usually better than trying to count vowels with a simple heuristic.

The overall architecture stays the same. The part that changes is where the program gets trustworthy syllable counts.

Common Pitfalls

Treating haiku generation as a word-count problem instead of a syllable-count problem breaks the form immediately.

Using one random vocabulary list with no theme or grammar rules often produces output that is valid on paper but incoherent to read.

Relying on naive vowel counting for English syllables creates many incorrect classifications.

Using a tiny word bank without enough variation makes every generated poem sound nearly identical.

Ignoring backtracking can trap the generator in dead ends when the remaining syllable count becomes impossible to satisfy.

Summary

  • A haiku generator needs reliable 5-7-5 syllable control first.
  • Grouping words by syllable count is the simplest workable design.
  • Themes and templates improve coherence far more than extra randomness does.
  • Backtracking helps when line construction has grammar or vocabulary constraints.
  • A real syllable dictionary usually matters more than a clever random-selection trick.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.