Sunday 17 July 2016

PrettyPrint

Print concentric rectangular pattern in a 2d matrix.
Let us show you some examples to clarify what we mean.
Example 1:
Input: A = 4.
Output:
4 4 4 4 4 4 4 
4 3 3 3 3 3 4 
4 3 2 2 2 3 4 
4 3 2 1 2 3 4 
4 3 2 2 2 3 4 
4 3 3 3 3 3 4 
4 4 4 4 4 4 4 
Example 2:
Input: A = 3.
Output:
3 3 3 3 3 
3 2 2 2 3 
3 2 1 2 3 
3 2 2 2 3 
3 3 3 3 3 



 int ** prettyPrint(int A, int *number_of_rows, int *number_of_columns) {  
   int i, j, k, top, bottom, left, right;  
   *number_of_rows = A * 2 - 1;  
   *number_of_columns = A * 2 - 1;  
   int **result = (int **)malloc(*number_of_rows * sizeof(int *));  
   for(i = 0; i < *number_of_rows; i++){  
     result[i] = (int *)malloc(*number_of_columns * sizeof(int));  
   }  
   top = 0; bottom = *number_of_rows - 1;  
   left = 0; right = *number_of_columns - 1;  
   while(left <= right && top <= bottom){  
     for(i = top; i <= bottom; i++){  
       result[i][left] = A;  
       result[i][right] = A;  
     }  
     for(i = left; i <= right; i++){  
       result[top][i] = A;  
       result[bottom][i] = A;  
     }  
     top++; bottom--;  
     left++; right--;  
     A--;  
   }  
   return result;  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive