Home > Mobile >  Code should not nest more than 3 control flow statements
Code should not nest more than 3 control flow statements

Time:11-24

I have to implement a bingo game and check for line, bingo or nothing for a given input where I get a 3x3 bingo card and next 15 numbers extracted.

I wrote the following function:

static int[,] ReadBingoCard(int rowsNumber, int columnNumber)
{
    int[,] card = new int[rowsNumber, columnNumber];

    for (int i = 0; i < rowsNumber; i  )
    {
        string[] array = Console.ReadLine().Split(' ');

        for (int j = 0; j < columnNumber; j  )
        {
            card[i, j] = Convert.ToInt32(array[j]);
        }
    }

    return card;
}

static int[] ReadNumbersExtracted(int numbersExtracted)
{
    int[] numbers = new int[numbersExtracted];

    for (int i = 0; i < numbersExtracted; i  )
    {
        numbers[i] = Convert.ToInt32(Console.ReadLine());
    }

    return numbers;
}

static bool CheckForBingo(int[,] bingoCard, int[] numbers)
{
    int numMatchesFound = 0;

    for (int row = 0; row < bingoCard.GetLength(0); row  )
    {
        for (int col = 0; col < bingoCard.GetLength(1); col  )
        {
            for (int numIndex = 0; numIndex < numbers.Length; numIndex  )
            {
                if (bingoCard[row, col] == numbers[numIndex])
                {
                    numMatchesFound  ;
                    break;
                }
            }
        }
    }

    return numMatchesFound == bingoCard.Length;
}
static bool CheckForLine(int[,] bingoCard, int[] numbers)
    {
        for (int row = 0; row < bingoCard.GetLength(0); row  )
        {
            int colMatchesInRow = 0;

            for (int col = 0; col < bingoCard.GetLength(1); col  )
            {
                for(int numIndex = 0; numIndex < numbers.Length; numIndex  )
                {
                    if (bingoCard[row, col] != numbers[numIndex])
                    {
                        continue;
                    }

                    colMatchesInRow  ;
                    break;
                }
            }

Due to some limitations of sonar analyzer I get the error:

S134 (Error) : Refactor this code to not nest more than 3 control flow statements for CheckForBingo function.

Is there a way to split this function to get rid of this error?

CodePudding user response:

Just use for-each to iterate through your 2d array:

static bool CheckForBingo(int[,] bingoCard, int[] numbers)
{
    int numMatchesFound = 0;
    foreach (var number in bingoCard)
    {
        for (int numIndex = 0; numIndex < numbers.Length; numIndex  )
        {
            if (number  == numbers[numIndex])
            {
                numMatchesFound  ;
                break;
            }
        }
    }
    
    return numMatchesFound == bingoCard.Length;
}
  •  Tags:  
  • c#
  • Related