1

I am atempting to transpose a matrix with wach row having a different number of columns. For example what I am trying is this

public Object[][] transpose (Object[][] data) {
    Object temp = new Object[data[0].length][];
    for (int i = 0; i < data.length; i++) {
         temp[i] = new Object[data[i].length];
         for ( int j = 0; j < data[i].length; j++) {
              temp[j][i] = data[i][j]
         }
    }
    return temp;
}

It is appearing that the fourth line is not working correctly which I am not quite sure how to work around it.

1
  • That code doesn't compile. It should be Object[][] temp, and you're missing a semi-colon after data[i][j]. Commented Jan 10, 2016 at 21:55

1 Answer 1

1

If your input looks like this:

[ [ 1, 2       ],
  [ 3, 4, 5, 6 ],
  [ 7          ] ]

The transposed result could be one of these:

        SIMPLE                 COMPACT
[ [    1, 3,    7 ],      [ [    1, 3, 7 ],
  [    2, 4, null ],        [    2, 4    ],
  [ null, 5, null ],        [ null, 5    ],
  [ null, 6, null ] ]       [ null, 6    ] ]

In either case, the result should have as many columns as the longest row, not the first row.

public static Object[][] transposeSimple(Object[][] data) {
    int maxLen = 0;
    for (Object[] row : data)
        if (row.length > maxLen)
            maxLen = row.length;
    Object[][] temp = new Object[maxLen][data.length];
    for (int i = 0; i < data.length; i++)
        for (int j = 0; j < data[i].length; j++)
            temp[j][i] = data[i][j];
    return temp;
}
public static Object[][] transposeCompact(Object[][] data) {
    int maxLen = 0;
    for (Object[] row : data)
        if (row.length > maxLen)
            maxLen = row.length;
    Object[][] temp = new Object[maxLen][];
    for (int i = 0; i < temp.length; i++) {
        for (maxLen = data.length; maxLen > 0; maxLen--)
            if (data[maxLen - 1].length > i)
                break;
        temp[i] = new Object[maxLen];
        for (int j = 0; j < maxLen; j++)
            if (i < data[j].length)
                temp[i][j] = data[j][i];
    }
    return temp;
}

Test

System.out.println(Arrays.deepToString(transposeSimple(new Object[][] {
        { 1, 2       },
        { 3, 4, 5, 6 },
        { 7          },
})));
System.out.println(Arrays.deepToString(transposeCompact(new Object[][] {
        { 1, 2       },
        { 3, 4, 5, 6 },
        { 7          },
})));

Output

[[1, 3, 7], [2, 4, null], [null, 5, null], [null, 6, null]]
[[1, 3, 7], [2, 4], [null, 5], [null, 6]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.