Tuesday, March 26, 2013

Characters in Pyramid Form Problem

Thought i would enter this world with a bang.. But for now i would begin posting some simple java codes. Maybe will help someone some time. Feel free to post if  you have a better approach.

So here's the code for printing a string array of  characters where you need to print each character in the pyramid form.
You are given the number of lines and the characters. Say if you have to print and array of chars:
A,B,C,D,E,F in the pyramid form in an 8 lined pyramid, it should look like this:

Here's what i have written:

Pyramid.java

 public class Pyramid {
StringBuffer buf;

public static void main(String args[]){

Pyramid p=new Pyramid();
int numberOfLines=8;
String[] input={"A","B","C","D","E","F"};
String output=p.output(numberOfLines, input).toString();
System.out.println("Result:\n" + output);
}
private StringBuffer output(int numberOfLines, String[] input){
buf=new StringBuffer();
for(int currentLine=1;currentLine<=numberOfLines;currentLine++){

int arrayIndex=0;  //this will keep track of the letter being print.

//to leave initial gaps
for(int k=0;k<numberOfLines-currentLine;k++)
buf.append(" ");

//to start printing letter in the line
for(int j=0;j<currentLine;j++){

//check if still chars available in the array
if(arrayIndex<input.length){
buf.append(input[arrayIndex]).append(" ");
arrayIndex++;
}
//else reset to first location
else{
arrayIndex=0;
buf.append(input[arrayIndex]).append(" ");
arrayIndex++;
}
}
buf.append("\n");
}
return buf;
}
}


So there you go.
Plus only a small mod is required if you want to print the chars all in succession. without beginning from A in ever line. Something like this:

All you need to do is move the 
                              int arrayIndex=0; 
outside the for loop so that the arrayindex is not initialised to 0 for everyline.

Cheers and good luck. :)

No comments:

Post a Comment