Coding Challenge 8: Problem 1: Check whether a Matrix is a Latin Square or not

Hello! So I’m doing a 30 day coding challenge where I solve around 3-5 questions per day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 8: Problem 1! Be sure to post your answers, queries etc in the comments!

Problem: Check whether a Matrix is a Latin Square or not (A Latin Square is a square matrix in which no value is repeated in a given row or column)

Sample input: {{1,2,3,4},
{2,3,4,1},
{3,4,1,2},
{4,1,2,3}}
Output: Matrix is Latin Sqaure

Sample input: {{1,2,3,4},
{1,3,1,1},
{3,4,1,2},
{4,4,2,3}}
Output: Matrix is not Latin Square

Solution:

package array;

public class Program008Latin_square {
	
	public static int check_duplicate (int [][] matrix, int element, int row ,int col,int n){
		int duplicate=0;
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++){
				if(i==row)
					if(element==matrix[i][j])
						duplicate++;
				if(j==col)
					if(element==matrix[i][j])
						duplicate++;
			}
		}
		
		return duplicate;
	}
	
	public static void main ( String args []){
		int [][] matrix= {{1,2,3,4}, {2,3,4,1}, {3,4,1,2}, {4,1,2,3}};
		int n=4, duplicate=0;
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++){
				System.out.printf("%4d", matrix[i][j]);
			}
			
			System.out.println();
		}
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++){
				int g=check_duplicate(matrix ,matrix[i][j],i,j,n);
				if (g>2)
					duplicate++;
			}
		}
		
		if(duplicate==0)
			System.out.println("Matrix is Latin Sqaure");
		else
			System.out.println("Matrix is not Latin Square");
	}

}

Download Code

Happy Learning!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close