как определить, имеет ли двумерный массив строку с 3 совпадающими последовательными столбцами - PullRequest
0 голосов
/ 30 апреля 2020

Я хочу проверить, есть ли в двумерном массиве строка с 3 совпадающими последовательными столбцами:

bool ScoreRijAanwezig(RegularCandies[,] speelveld)

Вот что у меня получилось:

public enum RegularCandies
{
    Jellybean,
    Lozenge,
    LemonDrop,
    GumSquare,
    LollipopHead,
    JujubeCluser
};

static void Main(string[] args)
{
    Program myProgram = new Program();
    myProgram.Start();
    Console.ReadKey();
}

void Start()
{
    RegularCandies[,] speelveld = new RegularCandies[10, 5];
    InitCandies(speelveld);
}

void InitCandies(RegularCandies[,] speelveld)
{
    Random rnd = new Random();

    for (int i = 0; i < speelveld.GetLength(0); i++)
    {
        for (int j = 0; j < speelveld.GetLength(1); j++)
        {
            speelveld[i, j] = (RegularCandies)rnd.Next(0, 6);
        }
    }
    PrintCandies(speelveld);
}

void PrintCandies(RegularCandies[,] speelveld)
{
    for (int i = 0; i < speelveld.GetLength(0); i++)
    {
        for (int j = 0; j < speelveld.GetLength(1); j++)
        {

            if (speelveld[i, j] == RegularCandies.Jellybean)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("#");
            }
            else if (speelveld[i, j] == RegularCandies.Lozenge)
            {
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.Write("#");
            }
            else if (speelveld[i, j] == RegularCandies.LemonDrop)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("#");
            }
            else if (speelveld[i, j] == RegularCandies.GumSquare)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("#");
            }
            else if (speelveld[i, j] == RegularCandies.LollipopHead)
            {
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.Write("#");
            }
            else if (speelveld[i, j] == RegularCandies.JujubeCluser)
            {
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.Write("#");
            }

            Console.ResetColor();
            Console.Write(" ");
        } Console.WriteLine();

    }
    ScoreRijAanwezig(speelveld);
}

bool ScoreRijAanwezig(RegularCandies[,] speelveld)
{
    int count = 1;

    for (int i = 0; i < speelveld.GetLength(0); i++)
    { // check which enum regularCandies shows up 3times in a row  next to   eachother
        // like this below; 
        //
        // row i--->   red    [blue   blue   blue]
        //             green   red    yellow green
        //             blue    green  green  purple
        //             purple  yellow purple yellow
        //
        //              ^
        //              |
        //
        //             col j
        // blue shows up 3 times a a row now break the loop and return true 

        for (int j = 0; j < speelveld.GetLength(1); j++)
        {

            if (speelveld[i, j] == RegularCandies.Jellybean)
            {
                count++;
                if (speelveld[i - 1, j] == RegularCandies.Jellybean)

                    if (count >= 3)
                    {
                        Console.WriteLine("Speelvelde SCORE 3X hetzelfde getal rood (JellyBean)");
                        return true;
                    }
            }
            else
            {
                count = 1;
            }
            if (speelveld[i, j] == RegularCandies.Lozenge)
            {
                count++;
                if (count >= 3)
                {
                    Console.WriteLine("speelvelde SCORE 3X hetzelfde getal oranje ");
                    return true;
                }
            }
            else
            {
                count = 1;
            }
        }

    }
    return false;
}

1 Ответ

1 голос
/ 30 апреля 2020

Вот один из способов сделать это.

Для каждой строки сохраните значение первого столбца в переменной и установите для переменной счетчика значение 1. Затем l oop через остальные столбцы и, если значение совпадает, увеличиваем счетчик, и если счетчик равен 3, мы нашли соответствующий последовательный набор и можем вернуть true. Если он не совпадает, тогда сбросьте itemToMatch на значение current столбца и установите счетчик обратно на 1. Если мы закончили sh последнюю строку и все еще не вернули true, то мы не нашли 3 последовательных совпадений, поэтому мы можем вернуть false:

for (var row = 0; row < speelveld.GetLength(0); row++)
{
    // Store the value of the first column and start our counter at 1
    var itemToMatch = speelveld[row, 0];
    var matchCount = 1;

    // Loop through the rest of the columns in the row
    for (var col = 1; col < speelveld.GetLength(1); col++)
    {
        // If this column matches, increment our counter
        if (speelveld[row, col] == itemToMatch)
        {
            matchCount++;

            // If we've found three matches, notify the user and return true
            if (matchCount == 3)
            {
                Console.WriteLine(
                    $"Row #{row + 1} has three matching items ({itemToMatch})");

                return true;
            }
        }
        // If the column didn't match, then store *this* column and reset the counter
        else
        {
            itemToMatch = speelveld[row, col];
            matchCount = 1;
        }
    }
}

// If we get this far, we never found three matches so notify the user and return false
Console.WriteLine("No rows have three consecutive matching columns");
return false;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...