C# Fastest way to search all letters in a row against dictionary

I am making a ruzzle-esqe type board game that has rows and columns of letters that a player moves (switches two pieces at a time) to make connected letters form a word. This match can only exist in row or column configuration.

I’ve run into performance, as well as design issues. So far i’m iterating each row in the board and concatenating a single letter at a time into a “currentWord” string for that row, then using LINQ to search the entire dictionary (120,000 string list) for a word that is the same length (i thought to save search time) as well as contains a match on the currentWord (which since currentWord contains a concatenated list, this does not find words in the middle of the row, only from origin, but thats another topic). Then I reverse the word and re-do the operation to check the other way.

In addition to the logic not producing the entirely desired results yet, whenever I move a piece the move doesn’t complete until the word check method is completed, which takes almost an entire second, so there is lag in the game play during piece moves.

Can somebody look at my method for searching the dictionary for board matches and give me some feedback or alternative code to speed up this operation or perform it more efficiently? Bonus points for giving tips about how to search every permutation of the row efficiently.

void FindAllWords()
    {
        //Properties
        _board.Rows = GetRows();
        _board.Columns = GetColumns();
        string currentWord = "";

        foreach (string row in _board.Rows)
        {
            foreach(char letter in row)
            {
                currentWord += letter;
                currentWord = currentWord.ToLower();
                if (currentWord.Length > 1 && currentWord.Length <= _rows)
                {
                    string reverseWord = currentWord.Reverse().ToString();
                    List<string> matchFoward = _wordGen.Dictionary.Where(x => x.Length == currentWord.Length).Where (y => y.Contains(currentWord)).ToList();
                    List<string> matchBackward = _wordGen.Dictionary.Where(x => x.Length == reverseWord.Length).Where (y => y.Contains(reverseWord)).ToList();
                    if (matchFoward.Count() > 0)
                    {
                        Debug.Log(matchFoward[0]);
                    }
                    if (matchBackward.Count() > 0)
                    {
                        Debug.Log(matchBackward[0]);
                    }
                }
            }
            currentWord = "";
        }
    }

Edit** I considered using multithreading but it seems like an unnecessary additional work load if there is a less complex solution.

1) don’t search the entire board every time a letter is moved. Only search the rows and columns that have actually changed. Any row or column that hasn’t changed hasn’t magically formed new words.

Becuase you move 2 letters, that should be at most 2 row and 2 columns that change. Those that intersect both letters. If they’re in the same row, or column, then that is reduced from 4 total to 3 total as they share a row or column.

Already cutting out a majority of your work.

2) Store the shortest word length, and the longest word length. No reason in testing the entire length of a row if it’s 16 characters long, and the longest word in your dictionary is 9.

3) Now for word matching… ok.

OK, you have your words stored in a collection of some sort called ‘Dictionary’. I don’t know what the collection type is, but because you’re using the ‘Where’ query on it, I’m going to suspect its a List. It also appears you already ‘ToLowered’ all the possible words, as you make sure to ToLower the word you compare into the list.

I’m not sure why you compare length and than contains though.

Here’s the thing, you’re just trying to test if two words match. You can just directly compare them. A word can only be the same length and one contain the other, if and only if they were the same word.

So you can test equality.

Here’s the thing… you’re still looping over an entire List of… 120,000 words!

There’s better collections for that.

Here’s the ‘HashSet’:
http://stackoverflow.com/questions/2667635/how-to-use-hashsetstring-contains-method-in-case-insensitive-mode

This is an unordered collection. The slot a member exists in depends on the hashcode generated for the object. A hashcode is an integer generated for some object, an object of some ‘value’ always generates the same hashcode, but 2 non equal ‘values’ will return a int that are most likely not equal. They might be… but most likely aren’t. The HashSet than modulos that int around a prime number, and places it in that slot. If 2 values happen to generate similar enough hashcodes that slot index are equal, but the values themselves aren’t equal, they’re put in a bucket together.

This allows for fast look up, because the only comparison test that occurs is between those values in the same bucket. A small, tiny, portion of the entire collection. When you have 120,000 entries, this is a HUGE savings. You’ll throw out comparing 119,000 of them easily.

Still toLower them though, it is still case sensitive.

Then all you’d have to do is test each possible word in a row/column, and just test if the dictionary ‘Contains’ it:

_wordGen.DictionaryHashSet.Contains(possibleWord)

If you end up having more complex string comparison, you can include a special IEqualityComparer to the HashSet to allow unequal words to compare the same (make sure they return the same hashcode if they’re equal).

4) Your ‘GetRows’ and ‘GetColumns’ appear to return strings. I’m assuming you just represent every row and column as one long string.

But aside from that I don’t know what your loops doing.

I don’t know what ‘_rows’ is, or the significance of its length. You also seem to be constructing ‘currentWord’ as a word from the first character in a row. Can you not have a word in the middle of a row?

“AZTUNCLEP”

And you never check words in columns, can you not have column words?

From here on out I don’t know how much I can help you, until I understand the exact rules of it. Because if you can have center words like my ‘uncle’ example… well it doesn’t appear your algorithm even does that.

Anyways, most of what I said should be a starter. We’ve filtered out 99% as unnecessary tests. So past that, even the most naive approach should be a significant improvement in speed.

1 Like

Excellent. You addressed and answered all of my questions. Ill get to work tonight, thank you.

I was able to convert my dictionary to a HashSet which reduced the dictionary lookup time to where there is no noticeable lag in the game. I also included a method to find all combinations of touching letters in every row and column and load them into a list which I can cross reference with my hashset dictionary. Now words can be anywhere on the board and will be spotted.

Here’s that code, as well as the code to find the actual words in the hashset.

Get All Row/Column touching combinations for lookup

List<string> CombinationsTolist()
    {
        List<string> combos = new List<string> ();
        string word = string.Empty;

        string searchRow = string.Empty;

        foreach (string row in _board.Rows)
        {
            for(int x = 0; x <= _rows; x++)
            {
                searchRow = row.Substring(x);
                for (int y = 0; y < searchRow.Length; y++)
                {
                    word += searchRow[y];
                    if (word.Length > 1)
                        combos.Add(word);
                }
                word = string.Empty;
            }
        }

        foreach (string col in _board.Columns)
        {
            for(int x = 0; x <= _columns; x++)
            {
                searchRow = col.Substring(x);
                for (int y = 0; y < searchRow.Length; y++)
                {
                    word += searchRow[y];
                    if (word.Length > 1)
                        combos.Add(word);
                }
                word = string.Empty;
            }
        }

        return combos;
    }

Do the lookup

    void FindAllWords()
    {
        _board.Rows = GetRows();
        _board.Columns = GetColumns();
        wordsToSearch = CombinationsTolist ();

        bool match = false;
        List<string> wordsToSearch = new List<string> ();

        foreach (string word in wordsToSearch)
        {
            if (word.Length >= 3)
            {
                match = _wordGen.Dictionary.Contains(word);
                if (match)
                {
                    Debug.Log (word);
                }
            }
        }
    }

*Edit, I could have used LINQ I think to reduce some of the nested loop structure but didn’t due to learning curve. I will try to go back and simplify.

Thanks again!

1 Like

If you have a question, you should post your own thread. This is over 2.5 years old. That looks like an array of strings for rows and columns…

1 Like