#include "IdanLib.h"
#include <stdio.h>

#define N 3

unsigned short MaxNumberInArray(unsigned short array[], int size)
{
    int max = array[ZERO],
        counter = ONE;
    for (counter = ONE; counter < size; counter++)
    {
        max = (array[counter] > max) ? array[counter] : max;
    }

    return (max);    
}

unsigned short MaxCountNumberInColumn(int mat[][N], unsigned short row_size ,unsigned short column)
{
    unsigned short counter_array[TEN] = { ZERO },
                   counter,
                   max;
    for (counter = ZERO; counter < row_size; counter++)
    {
        counter_array[mat[counter][column]]++;
    }

    max = MaxNumberInArray(counter_array, TEN);
    return (max);
    
}

unsigned short MaxCountNumberInRow(int mat[][N], unsigned short col_size ,unsigned short row)
{
    unsigned short counter_array[TEN] = { ZERO },
                   counter,
                   max;
    for (counter = ZERO; counter < col_size; counter++)
    {
        counter_array[mat[row][counter]]++;
    }

    max = MaxNumberInArray(counter_array, TEN);
    return (max);
    
}

BOOLEAN IsLatinSquare(int mat[][N], unsigned short row_size)
{
    unsigned short counter = ZERO;
    BOOLEAN is_latin_square = TRUE;
    while ((row_size - counter) * is_latin_square)
    {
        is_latin_square *= (MaxCountNumberInColumn(mat, row_size, counter) == ONE) *
                           (MaxCountNumberInRow(mat, row_size, counter) ==  ONE);
        counter++;
    }
    
    return (is_latin_square);
}

unsigned short InputUnsignedShort()
{
    unsigned short number;
    scanf("%hu", &number);

    return (number);
}

void InputMatrix(int mat[][N], unsigned short row_size)
{
    unsigned short counter,
                   area = row_size * row_size;
    for (counter = ZERO; counter < area; counter++)
    {
        scanf(" %d", &mat[counter / row_size][counter % row_size]);
    }
    
}
  
void OutputPrintRequestForMatrix()
{
    printf("Enter 9 numbers for matrix: ");
}

void OutputPrintLatinSquare(BOOLEAN is_latin_square)
{
    printf("This is latin square: %hu\n", is_latin_square);
}

void OutputPrintMatrix(int mat[][N], unsigned int row_size, unsigned int column_size)
{
    unsigned int counter_row,
                 counter_col;
    for (counter_row = ZERO; counter_row < row_size; counter_row++)
    {
        for (counter_col = ZERO; counter_col < column_size; counter_col++)
        {
            printf("%d, ", mat[counter_row][counter_col]);
        }
        printf("\n");
    }
}

void main(void)
{
    int mat[N][N] = { ZERO };
    OutputPrintRequestForMatrix();
    InputMatrix(mat, N);
    OutputPrintMatrix(mat, N, N);
    OutputPrintLatinSquare(IsLatinSquare(mat, N));
}