I have an input checker class with some RegExes, and I have converted some of the loops to lambdas. Am I doing it right? They seem to work fine, but I'm new to Lambdas. Does this offer a performance benefit over the commented implementation? Should I try implementing the first one as a lambda, and if so, how? Thanks in advance!
public static class DataChecker
{
public static bool IsGameInputDataValid(string[] dataFile)
{
if (dataFile.Length < 5)
{
return false;
}
var regexList = new List<Regex>();
regexList.Add(new Regex("^\\d\\s\\d$"));
regexList.Add(new Regex("^(\\d,\\d )*(\\d,\\d)$"));
regexList.Add(new Regex("^\\d\\s\\d$"));
regexList.Add(new Regex("^\\d \\d [NESW]{1}$"));
regexList.Add(new Regex("^[RLM]{1}( [RLM]{1})*$"));
//cant figure this one out as lambda... but should it even be converted for performance reasons?
for (int i = 0; i < 4; i++)
{
if (!regexList[i].IsMatch(dataFile[i]))
{
return false;
}
}
var listOfMoves = dataFile.Select(x => x).Skip(4).ToList();
//instead of:
// for (int i = 4; i<countOfLinesInInputFile; i++)
// {
// listOfMoves.Add(lines[i]);
// }
var areaAnyMoveSequencesInvalid =
listOfMoves.Select(x => regexList[4].IsMatch(x)).ToList()
.Any(y => y == false);
if (areaAnyMoveSequencesInvalid)
{
return false;
}
// instead of:
// foreach (var line in listOfMoves)
// {
// if (!regexList[4].IsMatch(line))
// {
// return false;
// }
// }
return true;
}
}
edit: Originally I wanted the question to only focus on the lambdas, but I got a lot of responses for the RegExes as well. Therefore I'll add the missing parts to make sense of that. It's a turtle-moving game in 2-dimensional x,y coordinates map.
Sample data file:
5 4
1,1 1,3 3,3
4 2
0 1 N
R M L M M
R M M M
M R M M M M
M R M M
M M M
Rules: The first line should define the board size • The second line should contain a list of mines (i.e. list of co-ordinates separated by a space) • The third line of the file should contain the exit point. • The fourth line of the file should contain the starting position of the turtle. • The fifth line to the end of the file should contain a series of moves.
Where: R: Rotate right L: Rotate left M: Move N,E,S,W: cardinal directions
I've updated the original with d+ instead of d, to allow for multiple digit coordinates:
regexList.Add(new Regex("^\\d+\\s\\d+$"));
regexList.Add(new Regex("^(\\d+,\\d+ )*(\\d+,\\d+)$|^$"));
regexList.Add(new Regex("^\\d+\\s\\d+$"));
regexList.Add(new Regex("^\\d+ \\d+ [NESW]{1}$"));
regexList.Add(new Regex("^[RLM]{1}( [RLM]{1})*$"));
dataFile
and explaination on what the expressions do and what data do you considerValid
. This would give us some idea on your question and we can help you with that. \$\endgroup\$