My problem is the if statement doesn't work and I don't know how to solve this question when I run the code always gives me a row score that's mean that there are three elements or more that are the same however this is not correct. extra details hereunder about the question
I have 2-dimensional array and I want to return true if there are 3 (or more) elements next to each other in one row, this is the question: the method returns true if there are 3 (or more) symbols next to each other in one row, otherwise it returns false. To determine '3 in a row' check all rows (one by one), and in each row remember the 'current candy' and set a counter to 1. If the next candy is the same (as the previous one) then increase the counter, otherwise reset the counter to 1 and set the 'current candy' again. If the counter becomes 3 then you can return true. → Check if there are (>=) 3 symbols adjacent in one row.
This is my Method
how can I improve it?
bool ScoreRowPresent(RegularCandies[,] playingField)
{
for (int i = 0; i < playingField.GetLength(0); i++)
{
int counter = 1;
RegularCandies candies = RegularCandies.JellyBean;
for (int x = 1; x < playingField.GetLength(1); x++)
{
if (candies==playingField[i,0])
{
counter++;
}
else
{
counter = 1;
candies = playingField[i, x];
}
if (counter >= 3)
{
return true;
}
}
}
return false;
}
Try with this:
bool ScoreRowPresent(RegularCandies[,] playingField)
{
for (var row = 0; row < playingField.GetLength(0); row++)
{
var candyToCount = playingField[row, 0];
var counter = 1;
for (var column = 1; column < playingField.GetLength(1); column++)
{
if (playingField[row, column] == candyToCount)
{
counter++;
}
else
{
counter = 1;
candyToCount = playingField[row, column];
}
if (counter >= 3)
{
return true;
}
}
}
return false;
}
Please let me know if this works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.