Hello guys!
I am training for interviews and got stuck at something. So I have a 2D array off characters. In which I have to find words in any direction. Every character which is in a word has to be marked, so later when all the words are found we can get all the characters which are NOT marked and with them we get a word. So I created a Cell object which has a .Char field which represents the character and an .isTaken field which represents if it was marked.
Here is my code, which I found online and I tried to rewrite it but i just can’t get it to mark the characters. If you have any idea please let me know!
public class WordFinder
{
public Cell[,] Cells;
public WordFinder(Cell[,] cells)
{
Cells = cells;
}
private Coordinate[] directions =
{
new Coordinate(-1, 0), // West
new Coordinate(-1,-1), // North West
new Coordinate(0, -1), // North
new Coordinate(1, -1), // North East
new Coordinate(1, 0), // East
new Coordinate(1, 1), // South East
new Coordinate(0, 1), // South
new Coordinate(-1, 1) // South West
};
public Range Search(string word)
{
for (int y = 0; y < Cells.GetLength(0); y++)
{
for (int x = 0; x < Cells.GetLength(1); x++)
{
if (Cells[y, x].Char == word[0])
{
Coordinate start = new Coordinate(x, y);
Coordinate end = SearchEachDirection(word, x, y);
if (end != null)
{
return new Range(start, end);
}
}
}
}
return null;
}
private Coordinate SearchEachDirection(string word, int x, int y)
{
char[] chars = word.ToCharArray();
for (int direction = 0; direction < 8; direction++)
{
Coordinate reference = SearchDirection(chars, x, y, direction);
if (reference != null)
{
return reference;
}
}
return null;
}
private Coordinate SearchDirection(char[] chars, int x, int y, int direction)
{
if (x < 0 || y < 0 || x >= Cellak.GetLength(1) || y >= Cellak.GetLength(0))
return null;
if (Cellak[y, x].Betu != chars[0])
return null;
if (chars.Length == 1)
{
return new Coordinate(x, y + 1);
}
char[] copy = new char[chars.Length – 1];
Array.Copy(chars, 1, copy, 0, chars.Length – 1);
return SearchDirection(copy, x + directions[direction].X, y + directions[direction].Y, direction);
}
}
public class Coordinate
{
public Coordinate(int x, int y)
{
X = x;
Y = y;
}
public int X { get; set; }
public int Y { get; set; }
}
public class Range
{
public Range(Coordinate start, Coordinate end)
{
Start = start;
End = end;
}
public Coordinate Start { get; set; }
public Coordinate End { get; set; }
}
no comments yet
Be the first to share what you think!
C# devs
null reference exceptions