Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transposing and Untransposing a String in java

I have been working on two methods that will Transpose and Untranspose a String respectively. The solutions that I have come up with both work to the best of my knowledge. I just want to know if I could have solved these problems in a simpler way. My code seems like it is too long for the task that is being performed. The first method, transpose(), will take a String as a parameter and transpose it. If "bridge" is entered, the output will be "bergid". Likewise, with the unTranspose() method, if the user enters "bergid", the output will be "bridge".

  public void transpose( String s )
  {
      String t = ""; 
      int end = s.length() - 1;


        for ( int i = 0; i < s.length()  / 2; i++ )
        {
            t += Character.toString( s.charAt( i ) ) + Character.toString( s.charAt( end ) );
            end--;
        }
        // Lenth of String is odd
        if ( s.length() % 2 == 1 )
        {
            // add character in middle of String to the end of the new String
            t+= Character.toString( s.charAt( s.length() / 2 ) );
        }

        System.out.println( t );
  }

    public void unTranspose( String s )
    {
    String t = ""; 

      // Length of String is odd
      if ( s.length() % 2 == 1 )
      {
      for ( int i = 0; i < s.length(); i+=2 )
      {
        t+= Character.toString( s.charAt( i ) );
      }

      for ( int i = s.length() - 2; i > 0; i -= 2 )
      {
        t += Character.toString( s.charAt( i ) );
      }

         System.out.println( t );
      }



   // Length of String is even
   else if ( s.length() % 2 == 0 )
   {
    for ( int i = 0; i < s.length() - 1; i+=2 )
    {
       t+= Character.toString( s.charAt( i ) );
    }

    for ( int i = s.length() - 1; i > 0; i -= 2 )
    {
        t+= Character.toString( s.charAt( i ) );
    }


    System.out.println( t );
}
   }

My code looks horrible. I'm still not used to formatting my code correctly. Please bear with me.

Thanks for your time


Definition

         transpose
         --------->
"123Xcba"            "1a2b3cX"
        <-----------
        untranspose
like image 991
Will Avatar asked Feb 27 '23 05:02

Will


1 Answers

Using Recursion

public static String transpose(String str) {

    if (str == null || str.length() == 1 || str.length() == 2) {
        return str;
    } else {
        return str.substring(0, 1) + str.substring(str.length() -1, str.length()) + transpose(str.substring(1, str.length() -1) );
    }
}

public static String untranspose(String str) {
    if (str == null || str.length() == 1 ||str.length() == 2) {
        return str;
    } else {
        return  str.substring(0, 1) + untranspose(str.substring(2, str.length())) + str.substring(1, 2);
    }
}
like image 74
Lalith Avatar answered Mar 05 '23 15:03

Lalith