Re: Displaying a sin wave horizontally instead of vertically.
printdude1968@gmail.com wrote:
I have a program that I wrote which displays a sin wave vertically
down stdout
<SSCCE>
public static void main(String [] args)
{
char[] starHolder = new char[200];
java.util.Arrays.fill(starHolder, '*');
String allStars = new String(starHolder);
for (int degrees=0;degrees<=360;degrees++)
{
double radians=degrees*(Math.PI/180);
double sinX=(Math.sin(radians)*100);
double x = (sinX + 100);
int y = (int)x;
System.out.println( allStars.substring(0,y) );
}
}
}
</SSCCE>
The reason for the adding of 100 is to handle the sin values which are
negative and I'm thinking that using an absolute value would skew the
results.
What I'd like to be able to do is have my program display the sin wave
horizontally instead of vertically.
Very limited testing, use at your own risk:
import java.io.PrintStream;
public class HSin {
public static void main(String[] args) {
printSin(System.out, 40, 80, 10);
}
/**
* Print a horizontal sine wave, with wave and space below it filled
with "*".
*
* @param out
* Send it to out.
* @param wavelength
* Width in columns of one complete cycle.
* @param cols
* Total columns to print.
* @param amplitude
* Maximum deviation from median of the sine wave.
*/
public static void printSin(PrintStream out,
int wavelength, int cols, int amplitude) {
for (int position = amplitude; position >= -amplitude; position--) {
for (int col = 0; col < cols; col++) {
double angle = 2 * Math.PI * col
/ (double) wavelength;
if (Math.sin(angle) * amplitude >= position) {
out.print("*");
} else {
out.print(" ");
}
}
out.println();
}
}
}