How to check if two rows of a matrix are circular rotations of each other in Node.js

1 Answer

0 votes
function rotate_left_by_one(arr) {
    const arr_size = arr.length;
    let rotate_row = [];
          
    for (let i = 0; i < arr_size; i++) {
        rotate_row[i] = arr[i];
    }
      
    const first = arr[0];
      
    for (let i = 0; i < arr_size - 1; i++) {
        rotate_row[i] = rotate_row[i + 1];
    }
          
    rotate_row[arr_size - 1] = first;
      
    return rotate_row;
}
   
function compare_rows_with_rotation(matrix, row1, row2) {
    const cols = matrix[0].length
      
    let rotate_row = rotate_left_by_one(matrix[row1]);
      
    for (let j = 0; j < cols; j++) {
        if (rotate_row[j] != matrix[row2][j]) {
            return false;
        }
    }
       
    return true;
}
   
    
const matrix = [ [ 4,  7,  5, 18], 
                 [ 7,  5, 18,  4], 
                 [-9, -4, -3,  2], 
                 [-8, -3, -9,  4], 
                 [ 2,  6,  7, 24] ];
   
if (compare_rows_with_rotation(matrix, 0, 1)) {
    console.log("yes");
} else {
    console.log("no");
}
     
       
         
         
/*
run:
         
yes
         
*/

 



answered Jun 25, 2023 by avibootz
...