示例#1
0
        protected void GetRules(string prefixText)
        {
            Dawg <string> Dawg;
            var           PrefixText = DictionaryHelper.RemoveStressMarks(prefixText).ToLowerInvariant().Reverse();

            var fileBasedDictionary = new FileBasedDictionary(Context.Server);

            try
            {
                using (Stream ReverseDict = fileBasedDictionary.OpenReverseIndex())
                {
                    Dawg = Dawg <string> .Load(ReverseDict,
                                               Func =>
                    {
                        string s = Func.ReadString();
                        return(s == String.Empty ? null : s);
                    });
                }

                int PrefixLen = Dawg.GetLongestCommonPrefixLength(PrefixText);

                WriteJSONToResponse(Dawg.MatchPrefix(PrefixText.Take(PrefixLen))
                                    .GroupBy(kvp => kvp.Value, kvp => kvp)
                                    .SelectMany(g => g.Take(1))
                                    .Select(kvp => kvp.Value + DictionaryHelper.RuleLineDelimiter + new string(kvp.Key.Reverse().ToArray()))
                                    .Take(10)
                                    .ToArray());
            }
            catch (Exception e)
            {
                WriteJSONToResponse(new [] { "Доступ к словарю в данный момент отсутствует. Возможно происходит построение индексов." });

                Email.SendAdminEmail("GetRules", e.ToString());
            }
        }
示例#2
0
        public IEnumerable <string> GetWordsWithGivenPrefix(string prefix)
        {
            Queue <string> result = new();
            IEnumerable <KeyValuePair <string, bool> > wordsWithPrefix = Dawg.MatchPrefix(prefix);

            foreach (KeyValuePair <string, bool> wordWithPrefix in wordsWithPrefix)
            {
                result.Enqueue(wordWithPrefix.Key);
            }
            return(result);
        }
        /// <summary>
        /// Finds all occurances of a given word in the dictionary
        /// </summary>
        /// <param name="word">Word to search</param>
        /// <returns>A list of matches found in the dictionary. Can be empty if nothing was found.</returns>
        public List <DictionaryMatch> MatchWord(string word)
        {
            // We store our words in format
            // 'Word' + '\x01' + paradigm_id + '\x01' + paradigm_index

            List <DictionaryMatch> result = new List <DictionaryMatch>();
            // Our dictionary contains only lower case versions of words
            // We add '\x01' so that we get only the needed word variants
            // and not all words starting with it
            var pairs = m_dictionary.MatchPrefix(word.ToLower() + "\x01");

            // Dawg stores pairs of a string key and a payload.
            // We don't have payload and our data is entierly in keys
            foreach (var pair in pairs)
            {
                int paradigm      = Int32.Parse(pair.Key.Split('\x01')[1]);
                int paradigmIndex = Int32.Parse(pair.Key.Split('\x01')[2]);

                result.Add(new DictionaryMatch(word, paradigm, paradigmIndex));
            }

            return(result);
        }
示例#4
0
 public IEnumerable <KeyValuePair <string, ushort> > MatchPrefix(IEnumerable <char> word)
 {
     return(dawg.MatchPrefix(word));
 }
示例#5
0
 private static string MatchJoin(Dawg <bool> dawg, IEnumerable <char> prefix)
 {
     return(string.Join(",", dawg.MatchPrefix(prefix).Select(kvp => kvp.Key)));
 }
示例#6
0
        /// <summary>
        /// Builds all possible right parts for given anchor
        /// </summary>
        /// <param name="partialWord">Word preceding right part</param>
        /// <param name="anchor">Tile from which to build up right part</param>
        /// <param name="boardArray">Board to work with</param>
        /// <param name="validCrossChecks">List of valid cross checks for all empty tiles</param>
        /// <param name="validMovesList">List of valid moves that gets updated</param>
        /// <param name="boardIsHorizontal">Board is untransposed or transposed</param>
        /// <param name="boardBeforeMove">Board before any moves were generated</param>
        /// <param name="tileExtendedWith">Tile that was used to extend the right part</param>
        public void ExtendRight(string partialWord, int[] anchor, BoardTile[,] boardArray, Dictionary <BoardTile,
                                                                                                       List <CharTile> > validCrossChecks, HashSet <GeneratedMove> validMovesList, bool boardIsHorizontal, BoardTile[,] boardBeforeMove,
                                CharTile tileExtendedWith = null)
        {
            //If no tile is present..
            if (boardArray[anchor[0], anchor[1]].CharTile == null)
            {
                //If word up until current tile is valid..
                if (Helper.CheckWordValidity(Dawg, partialWord))
                {
                    //If the move (word, row and column indexes) has not been added already..
                    if (!Moves.Any(m => m.Word.Equals(partialWord)))
                    {
                        //Adds generated move to list of valid moves
                        Dictionary <BoardTile, CharTile> tilesUsed = new Dictionary <BoardTile, CharTile>();

                        //Adds tiles that were used in move
                        for (int i = 0; i < partialWord.Length; i++)
                        {
                            var letter    = partialWord[i];
                            var boardTile = boardArray[anchor[0], anchor[1] - partialWord.Length + i];

                            if (boardTile.CharTile != null)
                            {
                                tilesUsed.Add(boardTile, boardTile.CharTile);
                            }
                            else
                            {
                                tilesUsed.Add(boardTile, tileExtendedWith);
                            }
                        }
                        validMovesList.Add(new GeneratedMove(boardIsHorizontal, anchor[1] - partialWord.Length, anchor[1] - 1, anchor, tilesUsed, boardBeforeMove, RackOfCurrentPlayer));
                    }
                }

                //GEts all letters that can follow current right part word
                HashSet <string> labelsOfDawgEdges = new HashSet <string>(new DawgEdgeEqualityComparer());
                var wordsWithCommonPreffix         = Dawg.MatchPrefix(partialWord);
                foreach (var word in wordsWithCommonPreffix)
                {
                    labelsOfDawgEdges.Add(word.Key.Substring(partialWord.Length));
                }
                foreach (var label in labelsOfDawgEdges)
                {
                    //If the valid letter is in our rack and can be played on the board tile, places it and extends right again
                    //with the newly filled board tile used as anchor if board limit is not reached
                    if (label == "")
                    {
                        continue;
                    }
                    if (RackOfCurrentPlayer.CheckIfTileIsInRack(label[0], true) &&
                        (!validCrossChecks.Any(c => c.Key == boardArray[anchor[0], anchor[1]]) ||
                         validCrossChecks.Any(c => c.Key == boardArray[anchor[0], anchor[1]] && c.Value.Any(x => x.Letter == label[0]))))
                    {
                        CharTile tileToWorkWith = null;
                        if (RackOfCurrentPlayer.CheckIfTileIsInRack(label[0], false))
                        {
                            tileToWorkWith = Dictionary.CharTiles.Where(c => c.Letter == label[0] && c.Score != 0).FirstOrDefault();
                        }
                        else
                        {
                            tileToWorkWith = Dictionary.CharTiles.Where(c => c.Letter == '*').FirstOrDefault();
                        }
                        RackOfCurrentPlayer.SubstractFromRack(tileToWorkWith);
                        boardArray[anchor[0], anchor[1]].CharTile = Dictionary.CharTiles.Where(c => c.Letter == label[0] && c.Score == tileToWorkWith.Score).FirstOrDefault();
                        if (anchor[1] < boardArray.GetLength(1) - 1)
                        {
                            ExtendRight(partialWord + label[0], new int[] { anchor[0], anchor[1] + 1 }, boardArray, validCrossChecks, validMovesList, boardIsHorizontal, boardBeforeMove, tileToWorkWith);
                        }

                        //Otherwise places the tile on the last empty square of the board, checks if its valid and doesn't attempt to extend anymore
                        else
                        {
                            var finalWord = partialWord + boardArray[anchor[0], anchor[1]].CharTile.Letter;
                            if (Helper.CheckWordValidity(Dawg, finalWord))
                            {
                                if (!Moves.Any(m => m.Word.Equals(finalWord)))
                                {
                                    Dictionary <BoardTile, CharTile> tilesUsed = new Dictionary <BoardTile, CharTile>();
                                    for (int i = 0; i < finalWord.Length; i++)
                                    {
                                        var letter    = finalWord[i];
                                        var boardTile = boardArray[anchor[0], anchor[1] - finalWord.Length + 1 + i];
                                        if (boardTile.CharTile != null)
                                        {
                                            tilesUsed.Add(boardTile, boardTile.CharTile);
                                        }
                                        else
                                        {
                                            tilesUsed.Add(boardTile, tileToWorkWith);
                                        }
                                    }
                                    validMovesList.Add(new GeneratedMove(boardIsHorizontal, anchor[1] - finalWord.Length + 1, anchor[1], anchor, tilesUsed, boardBeforeMove, RackOfCurrentPlayer));
                                }
                            }
                        }
                        RackOfCurrentPlayer.AddToRack(tileToWorkWith);
                        boardArray[anchor[0], anchor[1]].CharTile = null;
                    }
                }
            }
            //Otherwise if the current tile is already taken and not empty, used letter from board tile to build to the right again
            else
            {
                var tile = boardArray[anchor[0], anchor[1]].CharTile;
                HashSet <string> labelsOfDawgEdges = new HashSet <string>(new DawgEdgeEqualityComparer());
                var wordsWithCommonPreffix         = Dawg.MatchPrefix(partialWord + tile.Letter);
                foreach (var word in wordsWithCommonPreffix)
                {
                    labelsOfDawgEdges.Add(word.Key.Substring((partialWord + tile.Letter).Length));
                }

                //Extends right if any letters can follow the current right part
                if (labelsOfDawgEdges.Any() && anchor[1] < boardArray.GetLength(1) - 1)
                {
                    ExtendRight(partialWord + tile.Letter, new int[] { anchor[0], anchor[1] + 1 }, boardArray, validCrossChecks, validMovesList, boardIsHorizontal, boardBeforeMove, tile);
                }
            }
        }
示例#7
0
        /// <summary>
        /// Builds left part of word before anchor
        /// </summary>
        /// <param name="partialWord">Word preceding anchor. Might already be on the board or placed from previous LeftPart calls</param>
        /// <param name="limit">Limit of tiles we can place before anchor</param>
        /// <param name="anchor">Anchor from which to build left and right part</param>
        /// <param name="boardArray">Board array to work with (untransposed or transposed)</param>
        /// <param name="validCrossChecks">A list of crosschecks which say what tiles can be played in each board tile</param>
        /// <param name="validMovesList">A list of valid moves which is continuously updated</param>
        /// <param name="boardIsHorizontal">Board is untransposed or transposed</param>
        /// <param name="boardBeforeMove">Board before any moves were generated</param>
        public void LeftPart(string partialWord, int limit, int[] anchor, BoardTile[,] boardArray, Dictionary <BoardTile, List <CharTile> > validCrossChecks,
                             HashSet <GeneratedMove> validMovesList, bool boardIsHorizontal, BoardTile[,] boardBeforeMove)
        {
            //Tries to build all right parts for given left part
            ExtendRight(partialWord, anchor, boardArray, validCrossChecks, validMovesList, boardIsHorizontal, boardBeforeMove);
            if (limit > 0)
            {
                //Gets a list of letters that can follow the current left part and can be placed to the left of the anchor
                HashSet <string> labelsOfDawgEdges = new HashSet <string>(new DawgEdgeEqualityComparer());
                var wordsWithCommonPreffix         = Dawg.MatchPrefix(partialWord);
                foreach (var word in wordsWithCommonPreffix)
                {
                    labelsOfDawgEdges.Add(word.Key.Substring(partialWord.Length));
                }
                foreach (var label in labelsOfDawgEdges)
                {
                    if (label == "")
                    {
                        continue;
                    }
                    if (OriginalRackOfPlayer.CheckIfWordIsPlayable(partialWord + label[0]) &&
                        ((!validCrossChecks.Any(c => c.Key == boardArray[anchor[0], anchor[1] - 1]) ||
                          validCrossChecks.Any(c => c.Key == boardArray[anchor[0], anchor[1] - 1] &&
                                               c.Value.Any(x => x.Letter == label[0])))))
                    {
                        CharTile tileToWorkWith = null;
                        if (RackOfCurrentPlayer.CheckIfTileIsInRack(label[0], false))
                        {
                            tileToWorkWith = Dictionary.CharTiles.Where(c => c.Letter == label[0] && c.Score != 0).FirstOrDefault();
                        }
                        else
                        {
                            tileToWorkWith = Dictionary.CharTiles.Where(c => c.Letter == '*').FirstOrDefault();
                        }

                        //Rebuilds left part with new tiles
                        for (int i = 0; i < partialWord.Length; i++)
                        {
                            boardArray[anchor[0], anchor[1] - 1 - i].CharTile = null;
                        }
                        for (int i = 0; i < partialWord.Length; i++)
                        {
                            var tileToAdd = OriginalRackOfPlayer.GetTile(partialWord[i]);
                            boardArray[anchor[0], anchor[1] - partialWord.Length - 1 + i].CharTile = tileToAdd;
                        }
                        RackOfCurrentPlayer.SubstractFromRack(tileToWorkWith);
                        boardArray[anchor[0], anchor[1] - 1].CharTile = tileToWorkWith;
                        bool validPrefix = true;

                        //Checks if the newly formed left part's components are valid for the board
                        for (int i = 0; i < partialWord.Length; i++)
                        {
                            var boardTile = boardArray[anchor[0], anchor[1] - 1 - partialWord.Length + i];
                            if (!(!validCrossChecks.Any(c => c.Key == boardTile) ||
                                  validCrossChecks.Any(c => c.Key == boardTile &&
                                                       c.Value.Any(x => x.Letter == partialWord[i]))))
                            {
                                validPrefix = false;
                                break;
                            }
                        }

                        //If they are valid, call LeftPart again, which will call ExtendRight for all possible right moves and eventually try a new left part
                        if (validPrefix)
                        {
                            LeftPart(partialWord + label[0], limit - 1, anchor, boardArray, validCrossChecks, validMovesList, boardIsHorizontal, boardBeforeMove);
                        }
                        RackOfCurrentPlayer.AddToRack(tileToWorkWith);
                        boardArray[anchor[0], anchor[1] - 1].CharTile = null;

                        //Resets the left part once done
                        for (int i = 0; i < partialWord.Length; i++)
                        {
                            boardArray[anchor[0], anchor[1] - partialWord.Length - 1 + i].CharTile = null;
                        }
                    }
                }
            }
        }
示例#8
0
 public IEnumerable <string> GetWordsByPrefix(string prefix)
 {
     return(_dawg.MatchPrefix(prefix).Select(x => x.Key));
 }