How to check if all 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,  9, 16, 29], 
                 [ 7,  9, 16, 29,  4], 
                 [ 9, 16, 29,  4,  7], 
                 [16, 29,  4,  7,  9], 
                 [29,  4,  7,  9, 16] ];
   
const rows = matrix.length;
 
let all_rows_are_circular = true;
for (let i = 0; i < rows - 1; i++) {
    if (compare_rows_with_rotation(matrix, i, i + 1) == false) {
        all_rows_are_circular = false;
        break;
    }
}
 
 
if (all_rows_are_circular == true) {
    console.log("yes");
} else {
    console.log("no");
}
     
 
 
         
/*
run:
         
yes
         
*/

 



answered Jun 26, 2023 by avibootz
...