I have an assignment to code a method that will print values in a diamond pattern. For example, if the method is called like printNumberDiamond(2)
, then the results should look like:
" 0 "
" 010 "
"01210"
" 010 "
" 0 "
I have spent a ton of time on writing the code that does this, but I am sure that it's not the most efficient/clean way. I am hoping to learn new strategies for accomplishing this, because this was very difficult for me to complete, and I almost just gave up, but I got it to work:
public static void printNumberDiamond(int diaCenter)
{
printNumberDiamondTop(diaCenter);
printNumberDiamondBottom(diaCenter);
}
public static void printNumberDiamondTop(int diaCenter)
{
int maxAscendingRows = diaCenter + 1;
int maxColumnLength = diaCenter * 2 + 1;
int highestNbrForRow = 0;
for(int row = 0, rowCtr=0;row<=diaCenter;row++)
{
int thisColumnLength = 0;
int thisColumnMaxLeftSpaces = 0;
if(row >= maxAscendingRows)
{
thisColumnMaxLeftSpaces = (maxColumnLength - rowCtr) / 2;
rowCtr--;
}
else
{
thisColumnLength = maxColumnLength - row;
thisColumnMaxLeftSpaces = (thisColumnLength - row) / 2;
rowCtr++;
}
int nbrWritten = 0;
int nbrDescendingWritten = 0;
for(int col = 0;col < maxColumnLength;col++)
{
if(col < thisColumnMaxLeftSpaces)
{
System.out.print(" ");
}
else if(nbrDescendingWritten == 0 && nbrWritten > row)
{
System.out.print(" ");
}
else if(nbrWritten <= highestNbrForRow)
{
System.out.print(nbrWritten++);
nbrDescendingWritten = nbrWritten - 1;
}
else if(nbrWritten > highestNbrForRow)
{
System.out.print(--nbrDescendingWritten);
}
}
++highestNbrForRow;
System.out.print("\n");
}
}
public static void printNumberDiamondBottom(int diaCenter)
{
int maxColumnLength = diaCenter * 2 + 1;
int highestNbrForRow = 0;
for(int row = diaCenter;row>0;row--)
{
highestNbrForRow = row - 1;
int thisColumnMaxLeftSpaces = (maxColumnLength - highestNbrForRow * 2) / 2;
int nbrWritten = 0;
int nbrDescendingWritten = 0;
for(int col = 0;col < maxColumnLength;col++)
{
if(col < thisColumnMaxLeftSpaces)
{
System.out.print(" ");
}
else if(nbrDescendingWritten == 0 && nbrWritten > highestNbrForRow)
{
System.out.print(" ");
}
else if(nbrWritten <= highestNbrForRow && nbrWritten >= 0)
{
System.out.print(nbrWritten++);
nbrDescendingWritten = nbrWritten - 1;
}
else if(nbrWritten > highestNbrForRow)
{
System.out.print(--nbrDescendingWritten);
}
}
++highestNbrForRow;
System.out.print("\n");
}
printNumberDiamondTop
andprintNumberDiamondBottom
and spot places where you have common code, then extract this common code fragments to a separate methods. This will shorten your code and make it more clear. \$\endgroup\$ – RK1 Jul 7 '16 at 16:37