fork(1) 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. public static void main(String[] args) throws java.lang.Exception {
  10. printPattern(3);
  11. System.out.println("--------------");
  12. printPattern(4);
  13. System.out.println("--------------");
  14. printPattern(5);
  15. System.out.println("--------------");
  16. printPattern(6);
  17. System.out.println("--------------");
  18. }
  19. public static void printPattern(int i) {
  20. int num = i * i;
  21. int n = 1;
  22. int[][] matrixArray = new int[i][i];
  23.  
  24. for (int g = 0; g < i; g++) {
  25. for (int j = 0; j < i && n <= num; j++, n++) {
  26. if (g % 2 == 1) {
  27. matrixArray[i - (g + 1) / 2][j] = n;
  28. } else {
  29. matrixArray[g / 2][j] = n;
  30. }
  31. }
  32. }
  33.  
  34. for (int g = 0; g < i; g++) {
  35. for (int j = 0; j < i; j++) {
  36. System.out.print(matrixArray[g][j] + " ");
  37. }
  38. System.out.println();
  39. }
  40. }
  41.  
  42. }
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
1 2 3 
7 8 9 
4 5 6 
--------------
1 2 3 4 
9 10 11 12 
13 14 15 16 
5 6 7 8 
--------------
1 2 3 4 5 
11 12 13 14 15 
21 22 23 24 25 
16 17 18 19 20 
6 7 8 9 10 
--------------
1 2 3 4 5 6 
13 14 15 16 17 18 
25 26 27 28 29 30 
31 32 33 34 35 36 
19 20 21 22 23 24 
7 8 9 10 11 12 
--------------