Давайте сначала сделаем это для 1d-массива.
У нас есть массив с 8 числами.
public List<int> Get3InRow(int[] array)
{
List<int> found = new List<int>(); // the list of found numbers we return
int counter = 1; //counts the amount of identical numbers found.
int number = array[0]; //the number we are counting.
//now comes the for loop
for (int i = 1; i < 8; i++)
{
if (array[i] == number) counter++; // if we find a match counter goes up
else
{ //else reset the counter and search for new number.
number = array[i];
counter = 1;
}
if (counter == 3) found.Add(array[i]); // if we find 3 matching numbers ad it to the found list
}
return found;
}
теперь, чтобы сделать это с 2d-массивом.Все, что нам нужно сделать, это добавить еще один цикл.
public List<int> Get3InRow(int[,] array)
{
List<int> found = new List<int>(); // the list of found numbers we return
int counter = 1; //counts the amount of identical numbers found.
int number = 9; //the number we are counting. (we chose 9 because none of the numbers in the array have this number.)
//now comes the for loop
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (array[i,j] == number) counter++; // if we find a match counter goes up
else
{ //else reset the counter and search for new number.
number = array[i,j];
counter = 1;
}
if (counter == 3) found.Add(array[i,j]); // if we find 3 matching numbers ad it to the found list
}
}
//we repeat the for loops with i and j interchanged(in array[]) because now we want to check the other axis
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (array[j,i] == number) counter++; // if we find a match counter goes up
else
{ //else reset the counter and search for new number.
number = array[j,i];
counter = 1;
}
if (counter == 3) found.Add(array[j,i]); // if we find 3 matching numbers ad it to the found list
}
}
return found;
}