Re: Displaying a sin wave horizontally instead of vertically.
Chris Smith wrote:
....
Interestingly, it would be substantially more difficult to draw a single
line than it was to shade the entire area. In that case, you'd have to
figure out not just whether this cell is underneath the curve, but
whether this cell is on the curve. You couldn't just turn the ">=" into
"==", because the character cell is larger than a point on the curve and
you'd be very unlikely to get anything shaded at all in that case. You
would actually need to figure out the size of a character cell in terms
of x-values and angles from the graph, and then try to figure out
whether the curve passes anywhere through that box. That's starting to
become a rather involved problem.
Chris, I'm shocked at you. You are better than that at seeing the easy
ways of doing things. :-)
This task is an excellent example of a mixed domain application, one in
which at least two worlds meet. In this case, one domain is printing in
a rectangular grid. The other domain is the double precision floating
point approximation to the mathematics of sine waves.
In any mixed domain application, you should be continually asking
yourself "Would this be easier done in the other domain?". Trying to
work the single line requirement while looking at it from the point of
view of the sine wave comparison is as hard as Chris says. Doing it in
the rectangular grid printing domain is much easier.
Relative to the filled version, which asterisks should survive? The top
asterisk in each column. That would be easy to achieve if only we knew
whether the current column already has an asterisk in it:
public static void printSin(PrintStream out,
int wavelength, int cols, int amplitude) {
boolean[] hasAsterisk = new boolean[cols];
for (int position = amplitude; position >= -amplitude; position--) {
for (int col = 0; col < cols; col++) {
double angle = 2 * Math.PI * col
/ (double) wavelength;
if (!hasAsterisk[col] && Math.sin(angle) * amplitude >= position) {
out.print("*");
hasAsterisk[col] = true;
} else {
out.print(" ");
}
}
out.println();
}
}