'x,y calculation producing 3,3 rather than 1,2
Context: My exercise was to develop a c# program on the console (visual studio) where the user will write a x,y positions and the algorithm will find the final position (after different movement indications that will influence x and y).
The problem is that the results make no sensd. And I have no idea where and how I can fix it.
Indeed, here's an example of what suppose to happen on the console. The user types this:
0,0
3
r
u
u
And the result that should happen would be this :
1,2
but what really happen is :
3,3
And the result vary. Sometimes it's right, sometimes false. Any ideas ? Here's the code:
string ligne2; // THE USER WRITE X,Y
ligne2 = Console.ReadLine();
string[] ligne2Num = ligne2.Split(',');
int x;
int y;
x = int.Parse(ligne2Num[0]);
y = int.Parse(ligne2Num[1]);
//THE USER WRITE ON THE CONSOLE THE NUMBER OF MOVEMENT HE WANTS TO DO
int I;
I = int.Parse(Console.ReadLine());
Dictionary<string, string> Instructions = new Dictionary<string, string>();
//THE USER WRITE THE MOVEMENTS -> r = right, u = up, l = left, d = down
int i;
for (i = 0; i < I; i++)
{
Instructions.Add("d" + i, Console.ReadLine());
}
foreach (string item in Instructions.Values)
{
if (Instructions.ContainsValue("u") || Instructions.ContainsValue("U"))
{
y++;
}
if (Instructions.ContainsValue("l") || Instructions.ContainsValue("L"))
{
x--;
}
if (Instructions.ContainsValue("r") || Instructions.ContainsValue("R"))
{
x++;
}
if (Instructions.ContainsValue("d") || Instructions.ContainsValue("D"))
{
y--;
}
Console.WriteLine(x + "," + y);
Solution 1:[1]
If we look at your foreach statement, then you are not using the value from item, which is already an indicator that something is not right.
if you don't use the value, then a normal for loop is better. Although here, the foreach is actually fine we just need to ensure we use the value.
As you have 3 entries, then the loop will execute 3 times. But because you are looking through the whole dictionary (Instructions.ContainsValue) for each iteration, then you will execute the increment/decrement statements for each iteration, so this is why you end up with 3,3.
We can also simplify the if statements into a switch statement, and only check for the lowercase value. So then we end up with the folllowing.
foreach (string item in Instructions.Values)
{
switch(item.ToLower())
{
case "d": y--;
break;
case "u": y++;
break;
case "l": x--;
break;
case "r": x++;
break;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jason.kaisersmith |
