public bool AddWord(string word) { string[] wordArray = word.Select(x => x.ToString()).ToArray(); if (IsEmpty()) { AddFirstWord(wordArray); return(true); } int row = 0; bool matchFound = false; do { for (int col = 0; col < RowSize; col++) { InsertWordResult insertWordResult = AttemptToAddWordVertically(wordArray, row, col); matchFound = insertWordResult.Inserted; if (matchFound) { break; } } row += 1; } while (row + wordArray.Length <= RowSize && matchFound == false); return(matchFound); }
private InsertWordResult CanWordBeAddedVerticallyToRow(int wordLength, int row, int currentCol, string[] word) { bool letterMatch = false; bool letterMismatch = false; int currentRow = row; for (int i = 0; i < wordLength; i++) { if (Grids[currentRow, currentCol] == word[i]) { letterMatch = true; } else if (Grids[currentRow, currentCol] != word[i] && string.IsNullOrEmpty(Grids[currentRow, currentCol]) == false) { //The cell is not empty and there is a mismatch in the cell for the letter and letterMismatch = true; break; } currentRow += 1; } var insertResult = new InsertWordResult { Inserted = letterMatch && !letterMismatch, StartCell = Tuple.Create(row, currentCol), EndCell = Tuple.Create(currentRow, currentCol), Word = word.ToString() }; insertResult.Inserted = ValidateSuffixRule(insertResult); return(insertResult); }
private bool ValidateSuffixRule(InsertWordResult insertWordResult) { if (!insertWordResult.Inserted) { return(false); } int nextrow = insertWordResult.EndCell.Item1; int col = insertWordResult.EndCell.Item2; return(string.IsNullOrEmpty(Grids[nextrow, col])); }
private InsertWordResult AttemptToAddWordVertically(string[] word, int currentRow, int col) { int wordLength = word.Length; //Add only if first cell has been prepopulated with first word; if (string.IsNullOrEmpty(Grids[currentRow, col])) { return(new InsertWordResult()); } InsertWordResult wordInsertedResult = CanWordBeAddedVerticallyToRow(wordLength, currentRow, col, word); if (wordInsertedResult.Inserted) { AddWordVerticallyToRow(wordLength, currentRow, col, word); //InsertWordResults.Add(wordInsertedResult); } return(wordInsertedResult); }