Lem
BAN USERusing System.Collections.Generic;
using System.Diagnostics;
namespace SimplePlays
{
public class PathFinder
{
private readonly char[][] m_Board = new char[][]
{
new char[] {'a', 'b', 'c', 'd', 'e'},
new char[] {'f', 'g', 'h', 'i', 'j'},
new char[] {'k', 'l', 'm', 'n', 'o'},
new char[] {'p', 'q', 'r', 's', 't'},
new char[] {'u', 'v', 'w', 'x', 'y'},
new char[] {'z', ' '}
};
Dictionary<char, Position> m_NavigationBoard = new Dictionary<char, Position>();
public PathFinder()
{
initNavigationBoard();
}
private void initNavigationBoard()
{
for (int i = 0; i < m_Board.Length; i++)
{
for (int j = 0; j < m_Board[i].Length; j++)
{
m_NavigationBoard.Add(m_Board[i][j], new Position(i, j, m_Board[i].Length - 1));
}
}
}
public void PrintPath(string input)
{
if (string.IsNullOrEmpty(input))
{
return;
}
Position lastKnownPosition = new Position(0,0, 0);
foreach (char chr in input)
{
Position newPosition = m_NavigationBoard[chr];
PrintDirections(lastKnownPosition, newPosition);
lastKnownPosition = newPosition;
}
}
private void PrintDirections(Position from, Position to)
{
// for example, from Z to N
if (from.ColumnIndex < to.ColumnIndex && (to.ColumnIndex > from.MaxColumnIndex))
{
PrintRowsDirections(from, to);
PrintColumnDirections(from, to);
}
else
{
PrintColumnDirections(from, to);
PrintRowsDirections(from, to);
}
PrintStep(Directions.Ok);
}
private void PrintRowsDirections(Position from, Position to)
{
int tempIndex = from.RowIndex;
int tempDirection = from.GetRowDirection(to);
while (tempIndex != to.RowIndex)
{
// Do step
tempIndex += tempDirection;
//Print
PrintStep((tempDirection > 0) ? Directions.Down : Directions.Up);
}
}
private void PrintColumnDirections(Position from, Position to)
{
int tempColumnIndex = from.ColumnIndex;
int tempColumnDirection = from.GetColumnDirection(to);
while (tempColumnIndex != to.ColumnIndex)
{
// Do step
tempColumnIndex += tempColumnDirection;
//Print
PrintStep((tempColumnDirection > 0) ? Directions.Right : Directions.Left);
}
}
private void PrintStep(Directions step)
{
Debug.WriteLine(step);
}
enum Directions
{
Ok,
Up,
Down,
Left,
Right
}
[DebuggerDisplay("RI: {RowIndex}, CI: {ColumnIndex}")]
class Position
{
public Position(int rowIndex, int columnIndex, int maxColumnIndex)
{
RowIndex = rowIndex;
ColumnIndex = columnIndex;
MaxColumnIndex = maxColumnIndex;
}
public int RowIndex { get; set; }
public int ColumnIndex { get; set; }
public int MaxColumnIndex { get; set; }
public int GetRowDirection(Position newPosition)
{
if (newPosition.RowIndex >= this.RowIndex)
{
return 1;
}
return -1;
}
public int GetColumnDirection(Position newPosition)
{
if (newPosition.ColumnIndex >= this.ColumnIndex)
{
return 1;
}
return -1;
}
}
}
}
Idea:
- Lem December 06, 2013START and END should come in pairs, Like START1 - END1, ... START5 START6 ... END6 ... END5....
So, we need to find all intervals between pair-closed END (END5, not END6) and next START .
From this intervals, choose the longest one.