Files
crowdle/src/dict.zig
T
2026-06-11 21:08:15 -06:00

92 lines
2.3 KiB
Zig

const std = @import("std");
const Wordle = @import("wordle.zig");
/// A statically-initialized dictionary of all Wordle words.
var Dictionary: ?[]const Wordle.Word = null;
/// Gets or statically initializes the dictionary.
pub fn getDictionary() []const Wordle.Word {
if (Dictionary) |dict| {
return dict;
} else {
const dict = loadDict();
Dictionary = dict;
return dict;
}
}
/// Internal function to load the Wordle dictionary.
fn loadDict() []const Wordle.Word {
// directly embed dictionary contents
const src = @embedFile("dict.txt");
// count lines (words)
var num: u64 = 0;
for (src, 0..) |char, idx| {
_ = idx;
if (char == '\n') {
num += 1;
}
}
// allocate all words
const dictionary = std.heap.smp_allocator.alloc(Wordle.Word, num) catch unreachable;
// iterate over all lines
var lines = std.mem.splitSequence(u8, src, "\n");
var idx: usize = 0;
while (lines.next()) |line| {
// skip empty line at end
if (line.len == 0) {
continue;
}
// assert line is correct length
if (line.len != Wordle.WordLen) {
std.debug.panic("length of '{s}' mismatches {d} characters", .{ line, Wordle.WordLen });
}
// copy line bytes over
@memcpy(&dictionary[idx], line);
// increment dictionary entry
idx += 1;
}
// return complete dictionary
return dictionary;
}
/// Tests if a word is in the dictionary.
// TODO: binary search? need to assert that words are sorted
pub fn isInDictionary(word: Wordle.Word) bool {
// exhaustively search through dictionary
for (getDictionary()) |*entry| {
if (std.mem.eql(u8, entry, &word)) {
return true;
}
}
// if no word was found, return false
return false;
}
/// Asserts that a word literal is in the dictionary.
fn expectDictionary(word: Wordle.WordLiteral) !void {
try std.testing.expect(isInDictionary(Wordle.strToWord(word)));
}
/// Asserts that a word literal is *not* in the dictionary.
fn expectNotDictionary(word: Wordle.WordLiteral) !void {
try std.testing.expect(!isInDictionary(Wordle.strToWord(word)));
}
test "in dictionary" {
try expectDictionary("aback");
}
test "not in dictionary" {
try expectNotDictionary("hbzci");
}