NewsCrawler.org

Over-optimizing anagrams in Rust: a collision-free 64-bit ID per word

The author wrote a Rust solver for a Word Ladder[1] variant where a move is a single-letter change, deletion or addition, or turning a word into its anagram, and set out to speed it up after the first version took over a second to run. This post covers only one building block, an index of all anagrams in the Scrabble dictionary, which has 178,690 entries; a follow-up post will use it to solve the full ladder. The baseline implementation grouped words by their letter-sorted string and took 31 ms (173 ns per word), and its hash table had about 161,019 keys, so about that many Vec[2] allocations.

Replacing the per-word Vec allocations with a structure of heads, next and word arrays, where the high bit of a u32 distinguishes a stored value from an index into the arrays, brought the time down to 20 ms (112 ns per word). Packing 4-bit counts for all 26 letters into a u128 key cut it to 5.6 ms (31 ns per word), and switching to the rustc_hash FxHashMap[3] — faster as long as the inputs are not adversarial — brought it to 4.1 ms (23 ns per word).

The final trick is Gödel numbering[4]: each letter gets its own prime number, and a word is identified by the product of its letter-primes, a unique identifier that does not depend on letter order. The naive assignment a=2, b=3, c=5 overflows 64 bits at the dictionary's 365th word, ABORTIVENESSES, so the assignment was tuned not to common short words but to the patterns of the dictionary's 3157 15-character words: E is 2, I is 3, N is 19, S is 17, T is 29, and J is 101, since the longest word containing two J's is the 12-letter JEJUNENESSES. With these primes no word in the dictionary overflows 64 bits; the largest product is PSYCHOPATHOLOGY = 17763551150644031915, about 96.2% of the 64-bit number space, giving a collision-free identifier for the bag of letters in any word.

Read the original wiredream.comDiscussion

Sources

Published: First seen: Читать по-русски

Open as a page