Reputation: 3852
I have a 25 character long string where every subsequent 5 characters represent a row in the matrix.
String matrix="qwsedrhendtedksiehwnehsbt";
I am trying to transpose it using a function
public 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) );
}
}
produces
result="qtwbssehdernhwehneditsekd"
this isnt the expected result. the result must be
expectedResult="qrtiewheehsedhsenkwbddsnt"
I am not able to understand where I am going wrong
Upvotes: 0
Views: 986
Reputation: 37645
This method works for strings representing square matrices.
static String transpose(String s) {
int n = s.length();
int m = (int) Math.sqrt(n);
if (m * m != n)
throw new IllegalArgumentException();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n - 1; i++)
sb.append(s.charAt(i * m % (n - 1)));
sb.append(s.charAt(n - 1));
return sb.toString();
}
This more general version works for strings representing rectangular matrices.
static String transpose(String s, int rows, int columns) {
int n = s.length();
if (rows * columns != n)
throw new IllegalArgumentException();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n - 1; i++)
sb.append(s.charAt(i * columns % (n - 1)));
sb.append(s.charAt(n - 1));
return sb.toString();
}
Upvotes: 3
Reputation: 8011
I have an c++ implementation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* transpose (const char* matString, unsigned int col, unsigned int row)
{
char *answer = (char*)calloc(strlen(matString), sizeof(char));
unsigned int index = 0;
for(unsigned int i=0;i<col;i++)
{
for(unsigned int j=0;j<row;j++)
{
answer[index++] = matString[j * col + i];
}
}
return answer;
}
int main(int argc, char **argv)
{
printf("%s", transpose("ABCDEF", 3, 2));
return 0;
}
It gives output ADBECF
for the program the input matrix was
A-B-C
D-E-F
After transposition,.it's row will be column & columns will be row
A-D
B-E
C-F
& the string representation will look like ADBECF. For a quick explanation of the matrix transposition can have a look inside Matrix transposition
this is more generalized implementation of your problem specifies. It takes an row & col input for further generalization. Hope it helps you.
Upvotes: 0
Reputation: 31290
This transposes a nxn char matrix stored in a string of length n².
static String transpose( String s ){
char[] c = s.toCharArray();
int n = (int)Math.sqrt(s.length());
for( int i = 0; i < n; ++i ){
for( int j = i+1; j < n; ++j ){
char h = c[i*n+j];
c[i*n+j] = c[j*n+i];
c[j*n+i] = h;
}
}
return new String( c );
}
Upvotes: 2