Note 1: I already have the brute force, verbose, loopy messy code in place.
Note 2: Looking for more elegant ways of establishing this – “lesser” number of lines and clever logic.
Note 3: Not homework, I am a hobbyist trying to improve.
Function to be coded:
printNumericPyramid(int depth, String alignment, String orientation);
depth: +ve integer up to 4
alignment: one of “left”/”right”
orientation: one of “upright”/”inverted”
0 will always be at the apex, whether upright or inverted
0259/9520 will always be the height of the pyramid.
Samples calls and expected outputs:
printNumericPyramid(4, "left", "inverted");
9876
543.
21..
0...
printNumericPyramid(4, "right", "upright");
...0
..12
.345
6789
printNumericPyramid(4, "right", "inverted");
6789
.345
..12
...0
printNumericPyramid(4, "left", "upright");
0...
21..
543.
9876
It would be great if “lesser” number of lines could be the focus of the proposed solution. Not by removing all linebreaks:), but by minimization of code (even if it hurts readibility).
(First note that your method definition is error-prone: if an argument can only take two values you can use a boolean instead of a String. If you mispell “left” or “right” or “inverted” or “upright”, your method will work yet produce the wrong result)
If you want to focus on a low number of lines then you should not repeat yourself and you can make use of the ternary operator and of the available Java APIs.
You could write a very short solution based on very “smart” and totally unreadable code inside the following kind of loop:
However this may not end up being that easy to read and it’s going to be easy to get the logic wrong.
So I wrote another solution:
at each character you either print the next value (from 0 to 9) or you print a dot ‘.’.
when a line is “done”, I either add that line or that line reversed, depending on the value of the alignment parameter.
if the inversed representation is asked, you can simply reverse the collection