Question

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;
}
Was it helpful?

Solution

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

OTHER TIPS

Strings are immutable in Java, so you have a few options

  1. Write a wrapper for rotate(char [][]) that turns it back into a string array
  2. Modify the function to create a new array of strings from the input
  3. Create a data structure that holds the data in the most efficient format and then has getters that return it in the format you want it.

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).

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;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top