Created
March 2, 2017 08:26
-
-
Save Fullstop000/a233d5a50ceb26604f5256492391f541 to your computer and use it in GitHub Desktop.
This file contains 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 String triangleGenerator(int num, char letter ){ | |
if(num%2==0){ | |
num++ | |
} | |
// int num = 21; // input num (assume odd) | |
// char letter = 'A'; // input char | |
int rows = (num+1)/2; // the amount of rows | |
String result = ""; | |
int rowIdx = 1; // assume the idx of first row is 1 | |
while (rowIdx<=rows){ | |
int colIdx = 0; | |
// special case for 1st row | |
if (rowIdx==1){ | |
while(colIdx<num){ | |
// assume the idx of first letter in a row is 0 | |
if (colIdx==(num-1)/2){ | |
result+=letter; | |
}else { | |
result+=" "; | |
} | |
colIdx++; | |
} | |
}else if (rowIdx==rows){ | |
// special case for last row | |
while (colIdx<num){ | |
result+=letter; | |
colIdx++; | |
} | |
}else{ | |
// middle row case | |
int idx1 = (num-1)/2-(rowIdx-1); | |
int idx2 = (num-1)/2+(rowIdx-1); | |
while (colIdx<num){ | |
if (colIdx==idx1||colIdx==idx2){ | |
result+=letter; | |
}else { | |
result+=" "; | |
} | |
colIdx++; | |
} | |
} | |
result+="\n"; | |
rowIdx++; | |
} | |
// output result | |
// System.out.println(result); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment