Reputation: 11
Here's a problem. Please help me!
Enter a star bundle. (star='*') Suppose you input a bunch of stars one by one. Output by rotating it 90 degrees counterclockwise. In the first line, separate the star bundles by spaces. Array that stores star bundles has to be initialized with a space character(' '). From the second line, print a rotating star.
import java.util.Scanner;
public class Spin {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
int[][] A = new int[n][n];
int K = 1;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
A[i][j] = K++;
}
}
public static int[][] leftRotate(int n, int[][] A) {
int[][] B = new int[n][n];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
B[i][j] = A[j][n-i-1];
}
}
}
}
}
Upvotes: 0
Views: 208
Reputation: 159086
Take the input as a string using s = sc.nextLine()
. E.g. if user enters *** * **
, you get the same as s = "*** * **"
.
Split the line on spaces so you get String[] arr = {"***", "*", "**"}
.
Find the longest string, e.g. in this case you get longest = 3
.
The size of the array is the width of the resulting 3D grid, and the longest string is the height of the grid, so create the grid: char[][] grid = new char[longest][arr.length];
Fill the grid with spaces.
Now iterate arr
and build up each column of the grid, starting at the bottom.
... arr[0] *.. arr[1] *.. arr[2] *..
... -------> *.. -------> *.. -------> *.*
... *.. **. ***
Print the grid.
static void rotate(String input) {
String[] words = input.split(" ");
int rows = Arrays.stream(words).mapToInt(String::length).max().orElse(0);
char[][] grid = new char[rows][words.length];
Arrays.stream(grid).forEach(row -> Arrays.fill(row, ' '));
for (int i = 0; i < words.length; i++)
for (int j = 0; j < words[i].length(); j++)
grid[rows - j - 1][i] = words[i].charAt(j);
Arrays.stream(grid).forEach(System.out::println);
}
Tests
rotate("*** * **");
rotate("** **** *");
rotate("The quick brown fox jumps over the lazy dog");
Outputs
*
* *
***
*
*
**
***
kn s
cw pr y
eioxmeezg
hurouvhao
Tqbfjotld
Upvotes: 1