java - Building a right angled triangle with recursion -
i have homework required print asterick make draw triangle.
when drawtriangle(0);
*
when drawtriangle(1);
* **
when drawtriangle(2);
* ** * * ****
when drawtriangle(3);
* ** * * **** * * ** ** * * * * ********
when drawtriangle(4);
* ** * * **** * * ** ** * * * * ******** * * ** ** * * * * **** **** * * * * ** ** ** ** * * * * * * * * ****************
when drawtriangle(5);
* ** * * **** * * ** ** * * * * ******** * * ** ** * * * * **** **** * * * * ** ** ** ** * * * * * * * * **************** * * ** ** * * * * **** **** * * * * ** ** ** ** * * * * * * * * ******** ******** * * * * ** ** ** ** * * * * * * * * **** **** **** **** * * * * * * * * ** ** ** ** ** ** ** ** * * * * * * * * * * * * * * * * ********************************
any advice appreciated. cheers.
you've noticed height of triangle 2^n, i'm sure. know you'll need print out many rows. know need remember previous rows, if you're going copy them in way, know need have somewhere store them - perhaps vector?
for start, creating triangle leaning on left instead of right little easier. adding left padding make lean right easy once you've got going.
start single row containing "*": print it, , store string.
then 'n' times:
- make row's you've got 'square' adding spaces ends until equal length
- for each already existing row ( mean, not including new ones we're making below):
- print it, twice
- store printed new row
that's it. add spaces left of print out make lean on right.
(you might notice, once you've done this, can first step above inside for
loop below it. when 'make rows square' you're figuring out number of spaces add each row. adding many spaces between 2 copies of current row, in printout , in new row store, save printing out [and storing] unnecessary spaces.)
here couple of helpful string padding functions. padright
lengthen string n
characters wide adding spaces right. padleft
, guessed it, add spaces left:
public static string padright(string s, int n) { return string.format("%1$-" + n + "s", s); } public static string padleft(string s, int n) { return string.format("%1$#" + n + "s", s); }
one last opportunity bonus points: don't need store last half of rows print out.
Comments
Post a Comment