3
07/11/2024 12:49 pm
Inicio del tema
Write a JS function that finds the number of equal neighbor pairs inside a matrix of variable size and type (numbers or strings).
The input comes as array of arrays, containing string elements (2D matrix of strings).
Input:
[['2', '3', '4', '7', '0'],
['4', '0', '5', '3', '4'],
['2', '3', '5', '4', '2'],
['9', '8', '7', '5', '4']]
Output:
1
Input:
[['test', 'yes', 'yo', 'ho'],
['well', 'done', 'yo', '6'],
['not', 'done', 'yet', '5']]
Output:
2
The output is return value of you function. Save the number of equal pairs you find and return it.
1 respuesta
2
07/11/2024 12:50 pm
Here is the solution mate:
function equalNeighborsCount(matrix) { let neighbors = 0; for (let row = 0; row < matrix.length; row++) { for (let col = 0; col < matrix[row].length; col++) { if (row < matrix.length-1) { if (matrix[row][col] == matrix[row + 1][col]) { neighbors++; } } if(col<matrix[row].length) { if (matrix[row][col] == matrix[row][col + 1]) { neighbors++; } } } } return neighbors; } console.log(equalNeighborsCount([[2,2,5,7,4], [4,0,5,3,4], [2,5,5,4,2]] ));