I have a list of N consecutive vertical and horizontal sections of fixed dimensions in a form of a succession of directions (right → ; left ←; down ↓; up ↑). The program should return true if the sections intersect. For example: N = 6: { up, left, down, down, right, up} - return True. I got the coordinates for every section, but I don't really know how to finish this. Any ideeas?
static (int, int) GetCoordinates(string[] sectionDirection, int numberOfSections)
{
(int X, int Y) pos = (0, 0);
foreach (string move in sectionDirection)
{
switch (move)
{
case "left":
pos = (0, 0);
pos.X--;
break;
case "right":
pos = (0, 0);
pos.X++;
break;
case "down":
pos = (0, 0);
pos.Y--;
break;
case "up":
pos = (0, 0);
pos.Y++;
break;
}
}
return (pos.X, pos.Y);
}
static bool CheckSectionsIntersect(string[] sectionDirection, int numberOfSections)
{
// I need help here.
}
The simplest code change I can think of would be to use something that will remember all the visited locations and can tell you whether or not you have visited a location before. Such an object needs a way to add a location to its memory, and needs a way to test to see if a location is remembered.
Believe it or not, you can just use
stringto do this. Because a tuple will convert to a string as(0, 0)with parentheses and commas delimiting the fields, it's fine to just concatenate them all into a string and then usestring.Containsto see if a location exists. (This is kind of silly, and I'd prefer a HashSet instead of a string for efficiency, but you said in your comment you cannot.)It will build up a string that looks like:
(0, 0)(0, 1)(-1, 1)(-1, 0)...To remember a location, append it to the end of the string with the
+=operator. When you domemory += posthenposwill automatically get converted to a string usingToString().To check if a location exists, use
memory.Contains(pos.ToString()). In this case you have to explicitly convert the tuple to a string with.ToString()to pass it as an argument to.Contains.