How to resolve the algorithm Word wheel step by step in the JavaScript programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Word wheel step by step in the JavaScript programming language

Table of Contents

Problem Statement

A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the wheel or grid. Usually there will be a minimum word length of 3 or 4 characters. Each letter may only be used as many times as it appears in the wheel or grid.

Write a program to solve the above "word wheel" puzzle. Specifically:

A "word" is defined to be any string contained in the file located at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt. If you prefer to use a different dictionary,   please state which one you have used. Word wheel puzzles usually state that there is at least one nine-letter word to be found. Using the above dictionary, find the 3x3 grids with at least one nine-letter solution that generate the largest number of words of three or more letters.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Word wheel step by step in the JavaScript programming language

The provided JavaScript code defines a function called gridWords that takes a list of strings representing a grid of letters and a list of strings representing lexemes (words) and returns a list of lexemes that can be formed from the letters in the grid.

Here's a breakdown of the code:

  1. gridWords function:

    • Takes two arguments:
      • grid: A list of strings representing the rows of a grid of letters.
      • lexemes: A list of strings representing lexemes (words).
    • Returns a new list of strings containing the lexemes that can be formed from the letters in the grid.
  2. Inside the gridWords function:

    • wheel: A new string is created by joining all the strings in the grid list and then sorting the resulting string in ascending order. This string represents the letters in the grid arranged in a circular fashion.
    • wSet: A new Set is created from the wheel string. A Set is a collection of unique elements in JavaScript.
    • mid: The middle character of the wheel string is stored in the mid variable.
  3. The function then filters the lexemes list using the filter() method. The filter checks each lexeme using a callback function to determine if it should be included in the returned list.

  4. The callback function used in the filter:

    • Takes a single argument: w.
    • Converts w to lowercase and sorts its characters.
    • Checks if w has at least three characters and if all of its characters are present in the wSet.
    • Checks if w contains the mid character.
    • Calls the wheelFit function to verify that w can be formed using the letters in the wheel. If wheelFit returns true, it means w can be formed using the grid letters, and it is included in the returned list.
  5. wheelFit function:

    • Takes two arguments:
      • wheel: The sorted string representing the grid letters in a circular fashion.
      • word: The sorted string representing the lexeme being checked.
    • The function uses recursion to check if word can be formed using the letters in the wheel. It starts by comparing the first character of wheel with the first character of word. If they match, it moves on to compare the second characters, and so on. If it reaches the end of word without finding any mismatches, it returns true, indicating that word can be formed using the grid letters. Otherwise, it returns false.
  6. main function:

    • Defines the entry point of the script.
    • Calls the gridWords function with a grid of letters and a list of lexemes read from a file.
    • The result is a list of lexemes that can be formed from the grid letters, which is then joined into a newline-separated string and returned.
  7. Other utility functions:

    • lines: Splits a string into an array of strings based on newline characters.
    • readFile: Reads the contents of a file and returns a string.
    • sort: Sorts an array of elements in ascending order.
    • toLower: Converts a string to lowercase.

When you execute the script, it reads a list of words from a file (typically a dictionary), applies the gridWords function to filter the words based on the grid of letters, and prints the resulting list of words that can be formed using the grid letters.

Source code in the javascript programming language

(() => {
    "use strict";

    // ------------------- WORD WHEEL --------------------

    // gridWords :: [String] -> [String] -> [String]
    const gridWords = grid =>
        lexemes => {
            const
                wheel = sort(toLower(grid.join(""))),
                wSet = new Set(wheel),
                mid = wheel[4];

            return lexemes.filter(w => {
                const cs = [...w];

                return 2 < cs.length && cs.every(
                    c => wSet.has(c)
                ) && cs.some(x => mid === x) && (
                    wheelFit(wheel, cs)
                );
            });
        };


    // wheelFit :: [Char] -> [Char] -> Bool
    const wheelFit = (wheel, word) => {
        const go = (ws, cs) =>
            0 === cs.length ? (
                true
            ) : 0 === ws.length ? (
                false
            ) : ws[0] === cs[0] ? (
                go(ws.slice(1), cs.slice(1))
            ) : go(ws.slice(1), cs);

        return go(wheel, sort(word));
    };


    // ---------------------- TEST -----------------------
    // main :: IO ()
    const main = () =>
        gridWords(["NDE", "OKG", "ELW"])(
            lines(readFile("unixdict.txt"))
        )
        .join("\n");


    // ---------------- GENERIC FUNCTIONS ----------------

    // lines :: String -> [String]
    const lines = s =>
        // A list of strings derived from a single string
        // which is delimited by \n or by \r\n or \r.
        Boolean(s.length) ? (
            s.split(/\r\n|\n|\r/u)
        ) : [];


    // readFile :: FilePath -> IO String
    const readFile = fp => {
        // The contents of a text file at the
        // given file path.
        const
            e = $(),
            ns = $.NSString
            .stringWithContentsOfFileEncodingError(
                $(fp).stringByStandardizingPath,
                $.NSUTF8StringEncoding,
                e
            );

        return ObjC.unwrap(
            ns.isNil() ? (
                e.localizedDescription
            ) : ns
        );
    };


    // sort :: Ord a => [a] -> [a]
    const sort = xs =>
        Array.from(xs).sort();


    // toLower :: String -> String
    const toLower = s =>
        // Lower-case version of string.
        s.toLocaleLowerCase();


    // MAIN ---
    return main();
})();


  

You may also check:How to resolve the algorithm Soundex step by step in the TXR programming language
You may also check:How to resolve the algorithm Zero to the zero power step by step in the Swift programming language
You may also check:How to resolve the algorithm General FizzBuzz step by step in the SQL programming language
You may also check:How to resolve the algorithm Factors of an integer step by step in the Racket programming language
You may also check:How to resolve the algorithm Associative array/Creation step by step in the Pike programming language