The Anagram Game


Read {count} times since 2020

As you know, I have made Lobby – The localhost OS. I am in the process of adding more and more apps to it. This post explains how I created the Anagram game and the algorithm used for it.

You can download the app from here or search for “Anagram” in the Lobby Store.

The full source code is available on GitHub.

Anagram Game

Anagram Game

How It Works ?

There is a dictionary file containing many english words. When a user requests for a new puzzle, these happens :

  1. Choose random letters
  2. Loop through each words of dictionary and see if chosen letters is present in the word. The compatible words are added to an Array.
  3. The chosen letters and words are passed to the client side.

The client side (JavaScript) will display the letters and make the boxes for each words.

Dictionary

The dictionary consists of 51,853 words. You can see the 366KB file here.

Each words are separated by a newline (\n).

Algorithm

Here is how words are found out from the scrambled letters : Each word in the dictionary is looped over an the word is checked for same letters :

$avail = array(); // An array of scrambled letters
$dict = array(); // An array of words in dictionary
$pWords = array(); // An array of words that can be formed from the scrambled letters

foreach($dict as $word){
  $checked = array();
  $valid = true;
  $letters = str_split($word);
  
  $wordAvail = $avail;
  foreach($letters as $letter){
    $key = array_search($letter, $wordAvail);
    if($key === false){
      $valid = false;
    }
    unset($wordAvail[$key]);
  }
  if($valid == true){
    $pWords[$word] = 1;
  }
}

The $pWords will contain the words that can be formed from the scrambled letters.

Hack!

If you want to see the words before clicking “Solve”, you can use the Developer Tools of your browser to inspect the “data-word” attribute of each box.

Show Comments