[英]How to see if more than one of the same values is used in a row inside a 2D array - c#
[英]Three values in a row in a 2d array c#
我試圖讓我的程序檢查我的二維數組是否有3
彼此相鄰的相同值。
我目前有這個代碼,但是每當我count == 2
時它都會返回 true (抱歉它是荷蘭語):
bool ScoreRijAanwezig(RegularCandies[,] speelveld)
{
bool rij = false;
int count = 0;
` for (int i = 0; i < speelveld.GetLength(0); i++)
{
{
for (int j = 0; j < speelveld.GetLength(1) - 2; j++)
{
if (speelveld[i, j] == speelveld[i, j + 1])
{
count++;
if (speelveld[i, j + 1] == speelveld[i, j + 2])
count++;
if (count >= 3)
{
rij = true;
count = 0;
}
}
}
}
}
return rij;
}
我怎么知道它只在計數達到3或更大時才返回true
。
如果我理解正確,那么您正在連續尋找至少3
相等的值:
[1 2 3 4 5
5 7 8 9 1
3 6 6 6 7 <- three 6 in a row (what we are looking for)
3 7 8 9 0
3 5 3 5 3] <- just three 3, don't count
^
three 3 but in a column, don't count
讓我們實施它
// static: we don't use "this" in the method
static bool ScoreRijAanwezig(RegularCandies[,] speelveld) {
// row is too short
if (speelveld.GetLength(1) <= 2)
return false;
// scan each column
for (int i = 0; i < speelveld.GetLength(0); ++i) {
// we have at least 1 value in a row - it's a leftmost value
RegularCandies current = speelveld[i, 0];
int count = 1;
// we are scanning row:
// if we have the same value, let's increment check count
// if not, let's start from the value again
for (int j = 1; j < speelveld.GetLength(1); ++j) {
if (current == speelveld[i, j]) {
// increment and check: do we have 3 in the row?
if (++count >= 3)
return true;
}
else {
// sequence is broken, let's start again with count = 1
current = speelveld[i, j];
count = 1;
}
}
}
// entire array has been scanned, no three in the row found
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.