0

I have a string two-dimensional array which I need to format to look like a matrix. What I need is something like this:

   1  3  4
-124 52  6

 1  2  3  4
 5  6  7  8
-9 -8 -7 -6

  2   3   4   5
  7   8   9  10
-12 -11 -10  -9

I have to take into account the longest line in the matrix so the other lines of the matrix line up with it. I have already written code to determine which line is the longest since it will be based on that, but I don't know the exact way to format it.

This is the code where I determine the length of the longest line while converting a integer matrix into a string one:

String[][] solution = new String[m][n];
int l = 0;
for (int j = 0; j < m; j++) {
    int temp = 0;
    for (int k = 0; k < n; k++) {
        solution[j][k] = Integer.toString(matrix[j][k]);
        temp += solution[j][k].length();
    }
    if (l < temp) l = temp;
}
Community
  • 1
  • 1
Ge To
  • 107
  • 5

3 Answers3

0

So let's assume your array is stored as array[r][c]. So what you would want to do is go over the columns and rows. On a very simple basis what you can do is this:

if(c>r){Build a nested loop which row is the outer loop}

and do the opposite if it is r>c. Hope that helped

0

I'm assuming by "look like a matrix", you mean equidistant spacing between the elements of the matrix.

Here's something I came up with.

    1    3    4
 -124   52    6

  1  2  3  4
  5  6  7  8
 -9 -8 -7 -6

   2   3   4   5
   7   8   9  10
 -12 -11 -10  -9

The "trick" is to find the element that takes the most characters to print and use that length plus one to get the spacing between the cells on the line.

The String class has a format method that will format an int into a String. The formatter "%4d" will take an int and make it a four-character String with leading spaces.

We can construct a formatter by putting the three pieces of a formatter together.

String formatter = "%" + width + "d";

Here's the complete runnable code.

public class MatrixPrint {
    public static void main(String[] args) {
        MatrixPrint mp = new MatrixPrint();

        int[][] matrix1 = {{1, 3, 4},
                {-124, 52, 6}};
        System.out.println(mp.printMatrix(matrix1));

        int[][] matrix2 = {{1, 2, 3, 4},
                {5, 6, 7, 8},
                {-9, -8, -7, -6}};
        System.out.println(mp.printMatrix(matrix2));

        int[][] matrix3 = {{2, 3, 4, 5},
                {7, 8, 9, 10},
                {-12, -11, -10, -9}};
        System.out.println(mp.printMatrix(matrix3));
    }

    public String printMatrix(int[][] matrix) {
        int width = largestWidth(matrix) + 1;
        String formatter = "%" + width + "d";
        return printMatrixElements(matrix, formatter);
    }

    private int largestWidth(int[][] matrix) {
        int maxWidth = 0;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                int width = Integer.toString(matrix[i][j]).length();
                maxWidth = Math.max(maxWidth, width);
            }
        }
        return maxWidth;
    }

    private String printMatrixElements(int[][] matrix, String formatter) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                builder.append(String.format(formatter, matrix[i][j]));
            }
            builder.append(System.lineSeparator());
        }
        return builder.toString();
    }
}
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
  • While this is almost perfect, it puts unneeded spaces at the start of each line. I counteracted this by having two different formatters. – Ge To Mar 08 '21 at 18:52
0

You can use String.format method and represent each number as a string of a certain length, including hyphens for negative numbers. For example, if the number is already is in String format, you can use:

// format as a three-character string
String str = String.format("%3s", "-11");

If you have an array of such strings, you should know in advance the smallest negative number or the largest positive, i.e. the longest string. Your code might look something like this:

public static void main(String[] args) {
    printArray(new String[][]{
            {"1", "3", "4"},
            {"-124", "52", "6"}}, 4);
    printArray(new String[][]{
            {"1", "2", "3", "4"},
            {"5", "6", "7", "8"},
            {"-9", "-8", "-7", "-6"}}, 2);
    printArray(new String[][]{
            {"2", "3", "4", "5"},
            {"7", "8", "9", "10"},
            {"-12", "-11", "-10", "-9"}}, 3);
}
public static void printArray(String[][] arr, int length) {
    Arrays.stream(arr)
            .map(row -> Arrays.stream(row)
                    .map(str -> String.format("%" + length + "s", str))
                    .collect(Collectors.joining(" ")))
            .forEach(System.out::println);
}

Output:

   1    3    4
-124   52    6
 1  2  3  4
 5  6  7  8
-9 -8 -7 -6
  2   3   4   5
  7   8   9  10
-12 -11 -10  -9

See also:
Pascal's triangle 2d array - formatting printed output
How to get the following formatted output?