Skip to content

Instantly share code, notes, and snippets.

@gresrun
Last active August 29, 2015 14:22
Show Gist options
  • Save gresrun/602bd53dad80bb51bb94 to your computer and use it in GitHub Desktop.
Save gresrun/602bd53dad80bb51bb94 to your computer and use it in GitHub Desktop.
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