Last active
August 29, 2015 14:22
-
-
Save gresrun/602bd53dad80bb51bb94 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ASCIIDiamond { | |
public static void main(final String... args) { | |
printDiamond(Integer.parseInt(args[0])); | |
} | |
public static void printDiamond(final int size) { | |
if (size % 2 == 0) { | |
throw new IllegalArgumentException("Size must be an odd number"); | |
} | |
final int halfSize = (size / 2); | |
for (int i = 0; i < size; i++) { | |
final int offset = Math.abs(halfSize - i); | |
final String outsideSpaces = nSpaces(offset); | |
if (offset == halfSize) { | |
System.out.println(outsideSpaces + 'x' + outsideSpaces); | |
} else { | |
final String insideSpaces = nSpaces(((halfSize - offset) * 2) - 1); | |
System.out.println(outsideSpaces + 'x' + insideSpaces + 'x' + outsideSpaces); | |
} | |
} | |
} | |
private static String nSpaces(final int n) { | |
final StringBuilder buf = new StringBuilder(n); | |
for (int i = 0; i < n; i++) { | |
buf.append(' '); | |
} | |
return buf.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment