How to check if two rows of a matrix are circular rotations of each other in JavaScript

2 Answers

0 votes
function rotate_left_by_one(arr) {
    const arr_size = arr.length;
    const first = arr[0];
     
    for (let i = 0; i < arr_size - 1; i++) {
        arr[i] = arr[i + 1];
    }
       
    arr[arr_size - 1] = first;
}

function compare_rows(matrix, row1, row2) {
    const cols = matrix[0].length

    for (let j = 0; j < cols; j++) {
        if (matrix[row1][j] != matrix[row2][j]) {
            return false;
        }
    }
    
    return true;
}

 
const matrix = [ [ 4,  7,  9, 18], 
                 [ 7,  9, 18,  4], 
                 [-9, -4, -3,  2], 
                 [-8, -3, -9,  4], 
                 [ 2,  6,  7, 24] ];

rotate_left_by_one(matrix[0]);

if (compare_rows(matrix, 0, 1)) {
    console.log("yes");
} else {
    console.log("no");
}
  
    
      
      
/*
run:
      
"yes"
      
*/

 



answered Jun 24, 2023 by avibootz
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, 18], 
                 [ 7,  9, 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 24, 2023 by avibootz
edited Jun 25, 2023 by avibootz
...