Odin SolutionsOdin Solutions
🐵
Infinite Monkey Theorem
Week 14, 2026
All SolutionsCount occurrence of every word | greenya | Odin Solutions
package main
import "core:fmt"
import "core:strings"
import "core:slice"
import "core:time"
MONKEY_TXT :: #load("random-monkey-string.txt", string) or_else "thisabcisdefmonkeyghibusiness"
WORDS_TXT :: #load("words-strict.txt", string)
main :: proc () {
start := time.now()
defer fmt.printfln("\n/* Took %v */", time.since(start))
monkey_str := strings.trim(MONKEY_TXT, "\n\r\t ")
fmt.printfln("Monkey string has %d chars", len(monkey_str))
words_txt_trimmed := strings.trim(WORDS_TXT, "\n\r\t ")
words := strings.split_lines(words_txt_trimmed)
slice.sort(words[:])
fmt.printfln("Dictionary has %d words", len(words))
word_max_len := 0
for w in words do word_max_len = max(word_max_len, len(w))
fmt.printfln("Longest word has %d chars", word_max_len)
Group :: struct { words: [dynamic] string, total: int }
groups := make([] Group, word_max_len + 1)
prev_word: string
prev_word_count: int
for word, i in words {
if i % 1000 == 0 do fmt.printfln("Processing %d/%d...", i, len(words))
if prev_word != "" && prev_word_count == 0 && strings.has_prefix(word, prev_word) do continue
count := count_overlapping(monkey_str, word)
if count > 0 {
j := len(word)
append(&groups[j].words, word)
groups[j].total += count
}
prev_word = word
prev_word_count = count
}
for group, j in groups do if group.total > 0 {
assert(len(group.words) > 0)
assert(len(group.words[0]) == j)
fmt.println()
fmt.printfln("--- %d-Letter Words ---", j)
fmt.printfln("Total Count: %d", group.total)
fmt.printfln("Unique Count: %d", len(group.words))
fmt.print("Unique Words:")
for w in group.words do fmt.print("", w)
fmt.println()
}
}
count_overlapping :: proc (s, substr: string) -> (count: int) {
str := s
for {
i := strings.index(str, substr)
if i == -1 do break
count += 1
str = str[i+1:]
}
return
}