Skip to content

Instantly share code, notes, and snippets.

@Fullstop000
Created March 2, 2017 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fullstop000/a233d5a50ceb26604f5256492391f541 to your computer and use it in GitHub Desktop.
Save Fullstop000/a233d5a50ceb26604f5256492391f541 to your computer and use it in GitHub Desktop.
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