WIP dictionary
This commit is contained in:
10657
src/dict.txt
Normal file
10657
src/dict.txt
Normal file
File diff suppressed because it is too large
Load Diff
80
src/dict.zig
Normal file
80
src/dict.zig
Normal file
@@ -0,0 +1,80 @@
|
||||
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;
|
||||
|
||||
// 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| {
|
||||
// compare each letter at a time
|
||||
var match = true;
|
||||
for (entry, word) |entryLetter, wordLetter| {
|
||||
if (entryLetter != wordLetter) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// if every letter matches, return a complete match
|
||||
if (match) {
|
||||
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("alone");
|
||||
}
|
||||
|
||||
test "not in dictionary" {
|
||||
try expectNotDictionary("hbzci");
|
||||
}
|
||||
Reference in New Issue
Block a user