Advertisement
JeffGrigg

SquareWithDiagonalImpl

Aug 20th, 2018
447
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.68 KB | None | 0 0
  1. // JUnit test class:
  2. //  https://pastebin.com/yCnsggc2
  3.  
  4. import java.util.stream.Collectors;
  5. import java.util.stream.IntStream;
  6.  
  7. public class SquareWithDiagonalImpl {
  8.  
  9.     // Hard-coded implementation:
  10.     public static void main(String[] args) {
  11.         System.out.println("00000");
  12.         System.out.println("01000");
  13.         System.out.println("00200");
  14.         System.out.println("00030");
  15.         System.out.println("00004");
  16.     }
  17.  
  18.     public static void simplisticImplementation_withSeparatePrintStatements(final int size) {
  19.         for (int lineIndex = 0; lineIndex <= size; ++lineIndex) {
  20.             for (int columnIndex = 0; columnIndex <= size; ++columnIndex) {
  21.                 if (lineIndex == columnIndex) {
  22.                     System.out.print(lineIndex);
  23.                 } else {
  24.                     System.out.print("0");
  25.                 }
  26.             }
  27.             System.out.println();
  28.         }
  29.     }
  30.  
  31.     public static void simplisticImplementation_withTernaryOperator(final int size) {
  32.         for (int lineIndex = 0; lineIndex <= size; ++lineIndex) {
  33.             for (int columnIndex = 0; columnIndex <= size; ++columnIndex) {
  34.                 System.out.print((lineIndex == columnIndex) ? lineIndex : "0");
  35.             }
  36.             System.out.println();
  37.         }
  38.     }
  39.  
  40.     public static void streamImplementation(final int size) {
  41.         IntStream.rangeClosed(0, size).mapToObj((lineIndex) ->
  42.                 IntStream.rangeClosed(0, size).mapToObj((columnIndex) ->
  43.                         (lineIndex == columnIndex) ? String.valueOf(lineIndex) : "0"
  44.                 ).collect(Collectors.joining())
  45.         ).forEach(System.out::println);
  46.     }
  47.  
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement