JeffGrigg

AlternateStreamingCrossingStars

Mar 23rd, 2018
365
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.46 KB | None | 0 0
  1. /*
  2.  * Objective:  Print "cross" or "star" pattern from this post:
  3.  *      https://www.facebook.com/groups/java4developers/permalink/1742344979155475/
  4.  * JUnit tests:
  5.  *      https://pastebin.com/pVw3CUY0
  6.  * Additional tests, and tweaked for someone else's implementation:
  7.  *      https://pastebin.com/bZMmLnQs
  8.  */
  9.  
  10. import java.util.stream.IntStream;
  11.  
  12. public class AlternateStreamingCrossingStars {
  13.  
  14.     public static void printCrossingStars(final int n) {
  15.  
  16.         IntStream.rangeClosed(-n, n).forEach(lineIdx -> {       // For each line...
  17.  
  18.             IntStream.rangeClosed(1, n).forEach(column -> {     // For each "T" (multiple characters), left to right...
  19.                 final String leadingSpacesOrStars = nOf(column, (lineIdx == 0) ? '*' : ' ');    // Spaces -- except for the middle one.
  20.                 final char crossBar = (Math.abs(lineIdx) > column) ? ' ' : '*';     // = last character of each "T"
  21.                 System.out.print(leadingSpacesOrStars + crossBar);  // = all characters for one "T" (on one line)
  22.             });
  23.  
  24.             if (n > 0) {    // (special case for zero input -- of no output)
  25.                 System.out.println();
  26.             }
  27.  
  28.         });
  29.     }
  30.  
  31.     /**
  32.      * @return a <code>String</code> consisting of <code>count</code> copies of the character, <code>chr</code>.
  33.      */
  34.     private static String nOf(final int count, final char chr) {
  35.         return new String(new char[count]).replace('\0', chr);
  36.     }
  37.  
  38. }
Add Comment
Please, Sign In to add comment