In: Computer Science
In Java please You are given a matrix of characters representing a big box. Each cell of the matrix contains one of three characters: " / "which means that the cell is empty; '*', which means that the cell contains an obstacle; '+', which means that the cell contains a small box. You decide to rotate the big box clockwise to see how the small boxes will fall under the gravity. After rotating, each small box falls down until it lands on an obstacle, another small box, or the bottom of the big box. Given box, a matrix representation of the big box, your task is to return the state of the box after rotating it clockwise.
CODE:
package bigbox;
import java.util.Scanner;
public class BigBox
{
public static void main(String[] args)
{
//variable to store
number of rows and columns and taking it input from user
int row,col;
Scanner scan = new
Scanner(System.in);
System.out.print("Enter
the number of rows: ");
row =
scan.nextInt();
System.out.print("Enter
the number of columns: ");
col =
scan.nextInt();
//defining a char array
of the given size
char[][] arr = new
char[row][col];
for(int
i=0;i<row;i++)
for(int j=0;j<col;j++)
arr[i][j]=scan.next().charAt(0);
//calling the rotate big
box function to rotate the box
rotateBigBox(arr,row,col);
//printing the new big
box
for(int
i=0;i<row;i++)
{
System.out.println();
for(int j=0;j<col;j++)
System.out.print(arr[i][j]);
}
}
//this function rotates the big box
private static void rotateBigBox(char[][] arr,
int row, int col)
{
//for loop to iterate
rows
for(int
i=0;i<row;i++)
{ //for loop
to iterate column by colum value of a row from right to left
for(int j=col-2;j>=0;j--)
{
//if we find a small box
if(arr[i][j]=='+')
{
// we define a variable 'k' which is 1 more than curent 'j'
int k=j+1;
//we iterate using k till we reach end of the big box and till we
are finding '/' at the k-th place
while(k<col && arr[i][k]=='/')
{
//we swap if we find '/' in k-th place.
if(arr[i][k]=='/')
{
arr[i][k]='+';
arr[i][k-1]='/';
}
//we increment value of k
k++;
}
}
}
}
//rotating the box
clockwise
for (int i = 0; i <
row / 2; i++)
{
for (int j = i; j < col - i - 1; j++)
{
char temp = arr[i][j];
arr[i][j] = arr[row - 1 - j][i];
arr[row - 1 - j][i] = arr[row - 1 - i][col - 1 - j];
arr[row - 1 - i][row - 1 - j] = arr[j][col - 1 - i];
arr[j][row - 1 - i] = temp;
}
}
}
}
OUTPUT:
Enter the number of rows: 4
Enter the number of columns: 4
+ / + /
+ / * +
* * + /
+ + + /
/ * / /
+ * + /
+ / * +
+ + + +
Ask any question if you have in comment section below.
Please rate the answer.