Reputation: 899
How would i rotate a string array in java for a tetris game i am making. For example, the string array
[
"JJJJ",
"KKKK",
"UUUU"
]
would become
[
"UKJ",
"UKJ",
"UKJ",
"UKJ"
]
I can do it with a char matrix using this code
public char[][] rotate(char[][] toRotate)
{
char[][] returnChar = new char[toRotate[0].length][toRotate.length];
for(int rows = 0; rows<toRotate.length; rows++)
{
for(int cols = 0; cols<toRotate[0].length; cols++)
{
returnChar[cols][toRotate.length-1-rows]=toRotate[rows][cols];
}
}
return returnChar;
}
Upvotes: 2
Views: 2086
Reputation: 51483
With the Array String is similar to want you have done:
public static String[] rotate(String [] toRotate)
{
String [] returnChar = new String[toRotate[0].length()];
String [] result = new String[toRotate[0].length()];
Arrays.fill(returnChar, "");
for(int rows = 0; rows<toRotate.length; rows++)
for(int cols = 0 ; cols < toRotate[rows].length(); cols++)
returnChar[cols] = returnChar[cols] + toRotate[rows].charAt(cols);
for(int i = 0; i < returnChar.length; i++)
result[i] = new StringBuffer(returnChar[i]).reverse().toString();
return result;
}
I go through all char
in each String
on array toRotate
, concat this char (toRotate[rows].charAt(cols)
) to each String returnChar[cols]
on the array returnChar
Upvotes: 1
Reputation: 32333
This function does the job of converting the Strings into char[][]
so you can use your function.
public static String[] rotateString(String[] toRotate) {
char[][] charStrings = new char[toRotate.length][];
for(int i = 0; i < toRotate.length; i++) {
charStrings[i] = toRotate[i].toCharArray();
}
// This is YOUR rotate function
char[][] rotatedStrings = rotate(charStrings);
String[] returnStrings = new String[rotatedStrings.length];
for(int i = 0; i < rotatedStrings.length; i++) {
returnStrings[i] = new String(rotatedStrings[i]);
}
return returnStrings;
}
Upvotes: 0
Reputation: 13289
Strings are immutable in Java, so you have a few options
3 is essentially what you 'should' be doing. In a Tetris game, you would create a matrix of the size of the game field (possibly padded).
Upvotes: 1