fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12.  
  13. // Example usage
  14. String[] input = {"1", "2", "3", "x", "5", "6", "a", "baaaaaaasdfasdf", "c", "10",
  15. "11", "12", "13", "14", "15", "16"};
  16.  
  17. int numCols = 5; // Fixed number of columns
  18. int rows = (int) Math.ceil((double) input.length / numCols); // Calculate number of rows
  19. int[] maxColWidths = new int[numCols]; // Array to store max widths for each column
  20.  
  21. // Step 1: Calculate the max width for each column
  22. for (int i = 0; i < input.length; i++) {
  23. int colIndex = i % numCols;
  24. maxColWidths[colIndex] = Math.max(maxColWidths[colIndex], input[i].length());
  25. }
  26.  
  27. // Step 2: Print the table with the proper spacing
  28. for (int i = 0; i < rows; i++) {
  29. StringBuilder line = new StringBuilder();
  30. for (int j = 0; j < numCols; j++) {
  31. int index = i * numCols + j;
  32. if (index < input.length) {
  33. line.append(input[index]); // Append the string in the cell
  34.  
  35. // Calculate and add the padding
  36. if (j < numCols - 1) { // No padding needed after the last column
  37. int spaces = maxColWidths[j] - input[index].length() + 4; // 4 spaces between columns
  38. for (int k = 0; k < spaces; k++) {
  39. line.append(" ");
  40. }
  41. }
  42. }
  43. }
  44. System.out.println(line.toString().trim()); // Print the line
  45. }
  46.  
  47.  
  48.  
  49. }
  50. }
Success #stdin #stdout 0.07s 54876KB
stdin
Standard input is empty
stdout
1     2     3                  x     5
6     a     baaaaaaasdfasdf    c     10
11    12    13                 14    15
16