SHARE
TWEET

Untitled

a guest Jun 20th, 2019 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script>
  2.  
  3.  
  4. function numOfNeighbour( mat,  i,  j,rows,cols)
  5. {
  6.     var count = 0;  
  7.  
  8.     // UP
  9.     if (i > 0  && mat[i - 1][j]==='X')
  10.         count++;
  11.  
  12.     // LEFT
  13.     if (j > 0  && mat[i][j - 1]==='X')        
  14.         count++;
  15.  
  16.     // DOWN
  17.     if (i < rows-1  && mat[i + 1][j]==='X')        
  18.         count++;
  19.  
  20.     // RIGHT
  21.     if (j < cols-1 && mat[i][j + 1]==='X')        
  22.         count++;
  23.  
  24.     return count;
  25. }
  26.  
  27. function findPerimeter( mat)
  28. {
  29.     var perimeter = 0;
  30.     var rows=mat.length;
  31.     var cols=mat[0].length;
  32.  
  33.     // Traversing the matrix and finding ones to
  34.     // calculate their contribution.
  35.     for (var i = 0; i < rows; i++)
  36.         for (var j = 0; j < cols; j++)
  37.             if (mat[i][j] && mat[i][j]==='X')
  38.                 perimeter += (4 - numOfNeighbour(mat, i ,j,rows,cols));
  39.  
  40.     return perimeter;
  41. }
  42.  
  43. console.log("perimeter of ['XOOXO', 'XOOXO', 'OOOXO', 'XXOXO', 'OXOOO'] is ",findPerimeter(['XOOXO', 'XOOXO', 'OOOXO', 'XXOXO', 'OXOOO'])); //24
  44. console.log("perimeter of ['XOOO', 'XOXO', 'XOXO', 'OOXX', 'OOOO'] is "     ,findPerimeter(['XOOO', 'XOXO', 'XOXO', 'OOXX', 'OOOO'])); //18
  45. </script>
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top