Given a two dimensional array, print its mirror image if mirror is placed along one of the sides of the array.
First line of input will contain a number T = number of test cases. Each test case will contain two positive integers n and m (1<=n, m<=50) on a single line separated by space. Next n lines will each contain a string of exactly m characters. Next line will contain a character 'V' or 'H'. If character is V, mirror is placed vertically along the right-most column. If the character is H, the mirror is placed horizontally along the bottom-most row.
For each test case, print the n*m mirror image - n lines with strings of m character each. Print an extra empty line after output for each test case.
2
3 3
abc
def
ghi
V
3 4
1234
5678
9876
H
cba
fed
ihg
9876
5678
1234
MyApproach:
When I wrote the following Code.I am having problem while taking input. How to stop taking the input when the length of the input become equal to m characters.
Below is the code
int arr[][]=new int[n][m];
for(int j=0;j<n;j++)
{
for(int k=0;k<m;k++)
{
arr[j][k]=sc.nextInt();
//but if the input is in character how can i stop
//I think I need to read the characters character by character and stop hen m==3(as per Sample Input)
//How can I do that in java
}
System.out.println();
}
Try this
static void swap(String[][] array, int r1, int c1, int r2, int c2) {
String temp = array[r1][c1];
array[r1][c1] = array[r2][c2];
array[r2][c2] = temp;
}
static void vertical(String[][] array) {
int rows = array.length;
int cols = array[0].length;
for (int r = 0; r < rows; ++r)
for (int c = 0; c < cols / 2; ++c)
swap(array, r, c, r, cols - c - 1);
}
static void horizontal(String[][] array) {
int rows = array.length;
int cols = array[0].length;
for (int c = 0; c < cols; ++c)
for (int r = 0; r < rows / 2; ++r)
swap(array, r, c, rows - r - 1, c);
}
public static void main(String[] args) {
String s = ""
+ "2\n"
+ "3 3\n"
+ "abc\n"
+ "def\n"
+ "ghi\n"
+ "V\n"
+ "3 4\n"
+ "1234\n"
+ "5678\n"
+ "9876\n"
+ "H\n";
try (Scanner scanner = new Scanner(s)) {
int cases = scanner.nextInt();
for (int i = 0; i < cases; ++i) {
int rows = scanner.nextInt();
int cols = scanner.nextInt();
scanner.nextLine();
String[][] array = new String[rows][cols];
for (int r = 0; r < rows; ++r)
array[r] = scanner.nextLine().split("");
String operation = scanner.nextLine();
if (operation.equals("H"))
horizontal(array);
else
vertical(array);
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c)
System.out.print(array[r][c]);
System.out.println();
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.