Skip to content

Instantly share code, notes, and snippets.

@simonbrowndotje
Last active December 24, 2015 01:48
Show Gist options
  • Save simonbrowndotje/6725816 to your computer and use it in GitHub Desktop.
Save simonbrowndotje/6725816 to your computer and use it in GitHub Desktop.
Our first solution to the "Print Diamond" kata at the first Tech Tribes Jersey Coding Dojo (http://www.techtribes.je/events/50), by Simon Brown and Jason Roberts ... it could do with some further refactoring, validation, etc but it basically works.
public class PrintDiamond {
public static void main(String[] args) {
char letter = args[0].toUpperCase().charAt(0);
int letterAsNumber = ((int)letter - (int)'A') + 1;
int gridSize = (letterAsNumber * 2) - 1;
int numberOfSpacesAtEdge = (gridSize - 1) / 2;
int numberOfSpacesInMiddle = 0;
char letterToPrint = 'A';
for (int line = 1; line <= gridSize; line++)
{
printSpaces(numberOfSpacesAtEdge);
if (line == 1 || line == gridSize)
{
printLetter(letterToPrint);
}
else
{
printLetter(letterToPrint);
numberOfSpacesInMiddle = gridSize - 2 - numberOfSpacesAtEdge - numberOfSpacesAtEdge;
printSpaces(numberOfSpacesInMiddle);
printLetter(letterToPrint);
}
printSpaces(numberOfSpacesAtEdge);
System.out.println();
if (line >= ((gridSize+1)/2))
{
numberOfSpacesAtEdge++;
letterToPrint--;
}
else if (line < ((gridSize+1)/2))
{
numberOfSpacesAtEdge--;
letterToPrint++;
}
}
}
private static void printLetter(char letterToPrint) {
System.out.print(letterToPrint);
}
private static void printSpaces(int numberOfSpaces) {
for (int i = 1; i <= numberOfSpaces; i++)
{
System.out.print(" ");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment