GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Ask a Question

 

Start Coding Today

   

GeeksQuiz

GeeksforGeeksIDE

Data Structures

Algorithms

Interview Experiences

C Programming

C++ Programming

Java Programming

GATE CS

Books

write a program using java script that checks if two matrices have identical value in all the element

2 Answers

function is_equal_matrix(matrix1, matrix2){
	
	var row = 0,
		col = 0;
	var n1 = matrix1.length,
		m1 = matrix1[0].length;

	var n2 = matrix2.length,
		m2 = matrix2[0].length;		

	if (n1 != n2 || m1 != m2){
		return false;
	}

	for(; row < n1; row++){
		for(; col < m1; col++){
			if(matrix1[row][col] != matrix2[row][col]){
				return false;
			}
		}	
	}
	
	return true;	
}

a = [	[ 1, 2, 3 ], 
		[ 2, 3, 4 ], 
		[ 4, 5, 6 ] 
	]

b = [ 	[ 1, 2, 3 ], 
		[ 2, 3, 4 ], 
		[ 4, 5, 6 ] , 
		[6, 7, 8] 
	]

is_equal_matrix(a, b);

the function `is_equal_matrix` returns true if the given matrices are equal, and false otherwise

1. Calculate the number of rows and columns of each matrix

2. Number of columns of first and second (m1 and m2) and that of their rows must be equal  

3. if 2. is true, we check for all the values that are present in the matrices and if any value is not the same at the same location, we say the matrices are not the same or are not equal

4. If all the values are equal, meaning that we did not find any unequal value at the same coordinate(row, col) value, we indicate this as a true value as is evident from the last statement.

 

answered Apr 6 by harshitgarg

Harshit Garg, The whole program is wrong. Don't give newbies wrond codes as they will fall for it and they will fall hard.
Your program doesn't check for the second row and gives a result just after checking the first row for equality.

Because you have declared your col variable outside the first loop and assigned it a value of 0, It doesn't reset after the second loop runs three times. And as a result the second loop runs and makes the col variable 3 and it doesn't go to the second loop in the first iteration of the first loop.

answered Apr 17 by vmpltr
...