Print a sinusoidal wave (vertically)

42

4

Print a continuous sinusoidal wave scrolling vertically on a terminal. The program should not terminate and should continuously scroll down the wave (except until it is somehow interrupted). You may assume overflow is not a problem (i.e. you may use infinite loops with incrementing counters, or infinite recursion).

The wave should satisfy the following properties:

  • Amplitude = 20 chars (peak amplitude)
  • Period = 60 to 65 lines (inclusive)
  • The output should only consist of spaces, newline and |
  • After each line of output, pause for 50ms

Sample output:

                    |
                      |
                        |
                          |
                            |
                              |
                                |
                                 |
                                   |
                                    |
                                     |
                                      |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                       |
                     |
                   |
                 |
               |
             |
            |
          |
        |
       |
     |
    |
   |
  |
 |
 |
 |
 |
 |
 |
 |
  |
   |
    |
     |
      |
        |
         |
           |
             |
               |
                 |
                   |
                     |
                       |
                         |
                           |
                             |
                              |
                                |
                                  |
                                   |
                                    |
                                      |
                                      |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                    |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                       |
                     |
                   |
                 |
               |
             |
           |
          |
        |
       |
     |
    |
   |
  |
 |
 |
 |
 |
 |
 |
 |
  |
   |
    |
     |
       |
        |
          |
            |
             |
               |
                 |
                   |

The above output should go on forever unless otherwise interrupted, e.g. SIGINT or SIGKILL, or closing terminal window, or you power off your machine, or the Sun swallows the Earth, etc.

Shortest code wins.

Note. I am aware of a similar problem on Display Scrolling Waves but this isn't exactly the same. In my problem, the wave is not to be scrolled "in place" - just output it on a terminal. Also, this is an ascii-art problem, so don't use Mathematica to plot it.

user12205

Posted 2014-01-16T17:48:59.753

Reputation: 8 752

...or the Sun swallows the Earth, or the galaxy suffers from heat death, or highly intelligent beings tamper with the space time continuum – None – 2016-03-30T14:22:28.870

1Peak amplitude, peak-to-peak amplitude, or root-square amplitude? – DavidC – 2014-01-16T20:31:47.710

Peak amplitude. – user12205 – 2014-01-16T20:38:04.440

@David The Ecuador makes it pretty obvious. :-P – Doorknob – 2014-01-16T20:38:18.690

1Is it ok to draw a wave with just |s and no spaces? – Gelatin – 2014-01-17T01:23:30.087

@Gelatin Yes it is ok. – user12205 – 2014-01-17T08:19:44.173

Can a specific standard terminal width be assumed (e.g. 80)? – maxwellb – 2014-01-17T23:06:46.723

@maxwellb Terminal width is unspecified, i.e. do whatever you want :) – user12205 – 2014-01-17T23:17:13.650

@ace Wait, if I were to replace every space character in your sample output with |, it would be a valid program? You shouldn't say this because it changes the question. – Justin – 2014-01-19T09:49:10.347

@Quincunx it's not a wave then, is it? – user12205 – 2014-01-19T10:14:48.590

@ace Then why your response to this?

– Justin – 2014-01-19T23:36:22.877

@Quincunx Oh... I thought using no spaces mean something like printf("%*c")... sorry for the misunderstanding... – user12205 – 2014-01-19T23:46:21.053

1All answers yet are invalid. They also stop for SIGKILL not just for SIGINT. – Max Ried – 2014-04-04T09:02:59.547

1@Max Ried fine, I will change it to "should go on forever unless otherwise interrupted". – user12205 – 2014-04-04T10:28:54.967

Answers

12

APL (35)

(Yes, it does fit in 35 bytes, here's a 1-byte APL encoding)

{∇⍵+⌈⎕DL.05⊣⎕←'|'↑⍨-21+⌈20×1○⍵×.1}1

Explanation:

  • {...}1: call the function with 1 at the beginning
  • 1○⍵×.1: close enough for government work to sin(⍵×π÷30). (1○ is sin).
  • -21+⌈20: normalize to the range 1..40 and negate
  • '|'↑⍨: take the last N characters from the string '|' (which results in a string of spaces with a | at the end
  • ⎕←: display
  • ⌈⎕DL.05: wait 50 ms and return 1. (⎕DL returns the amount of time it actually waited, which is going to be close to 0.05, rounding that value up gives 1).
  • ∇⍵+: add that number (1) to and run the function again.

marinus

Posted 2014-01-16T17:48:59.753

Reputation: 30 224

2Darn... I thought trigonometric functions plus the time delay would leave you guys out – user12205 – 2014-01-17T20:22:17.417

2Here a 33 char one: {⎕←'|'↑⍨-⌈20×1+1○⍵⋄∇.1+⍵⊣⎕DL.05}0 – Tobia – 2014-01-18T00:03:35.207

3@ace LOL. You should check APL out, it's not a novelty language. It's very old and has been in use in large systems for decades. It's quite unique, compared to anything else. IMHO the symbols make it much more readable that the ASCII-only derivatives (J) – Tobia – 2014-01-18T00:16:31.233

22

C, 74 73 70 69 67 characters

67 character solution with many good ideas from @ugoren & others:

i;main(j){main(poll(printf("%*c|\n",j=21+sin(i++*.1)*20,0),0,50));}

69 character solution with while loop instead of recursion:

i;main(j){while(printf("%*c|\n",j=21+sin(i++*.1)*20,0))poll(0,0,50);}

Approaching perl territory. :)

treamur

Posted 2014-01-16T17:48:59.753

Reputation: 581

1This was inspired by @ace's own C answer. – treamur – 2014-01-16T21:41:26.087

2I think you could use 5E4 instead of 50000. – musiphil – 2014-01-17T00:00:38.780

2I think you could use *.1 instead of /10. – moala – 2014-01-17T01:58:48.087

1@musiphil, I also thought about using 5E4, but it turns out that it does not work: Without showing the compiler usleep() prototype, you would have to explicitly cast the 5E4. – treamur – 2014-01-17T05:32:46.557

@moala, thanks! Using *.1 instead of /10 seems to work. – treamur – 2014-01-17T05:33:27.093

@treamur: Thanks for the info. I also considered the possibility of a type error, but pre-ISO C was so archaic that I couldn't figure out the rules exactly. :) – musiphil – 2014-01-17T09:31:18.510

2You can cut out two more characters by moving the assignment to j into the printf, like this: printf("%*s\n",j=21+sin(i++*.1)*20,"|"). The resulting type is still int so it's a valid field width argument. – Art – 2014-01-17T10:17:55.810

1One more character by replacing usleep(50000); with poll(0,0,50);. – Art – 2014-01-17T10:24:04.840

1"%*s", where have you been all my life? +1 just for that. – primo – 2014-01-17T11:31:41.240

@Art, totally awesome, thanks! Implemented both of your ideas. I had been thinking of poll() myself, but I mistakenly landed my eyes on ppoll() parameter list on the manual page, so I discarded the idea. I was too hasty. Very nice that you brought the idea up again. :) – treamur – 2014-01-17T11:39:58.200

main(poll(!printf(...),0,50)); saves a character. – ugoren – 2014-01-19T08:04:01.540

@ugoren, totally so! Thank you for the tip. :) – treamur – 2014-01-19T08:50:15.083

@treamur - Two ugly ideas - 1. Omit ! (with 0 FDs, poll doesn't use the pointer). 2. Use %*c| with 0 (prints invisible NUL characters). – ugoren – 2014-01-19T09:33:54.383

@ugoren, brilliant ideas again, thanks! I added them to the answer. – treamur – 2014-01-19T15:20:37.003

12

Mathematica 121 104 80 67 64

n=1;While[0<1,Spacer[70 Sin[n Pi/32]+70]~Print~"|";Pause@.05; n++]

sine

DavidC

Posted 2014-01-16T17:48:59.753

Reputation: 24 524

question says not to use mathematica to plot it. is this different than that somehow? – Malachi – 2014-01-16T23:37:08.157

13@Malachi Yes. This uses mathematica to calculate it, just like any other answer. Using mathematica to plot would be telling mathematica to plot x=20*sin(pi*y/30)+20 or something similar. – Justin – 2014-01-16T23:49:48.790

ok I get what you are saying thank you for the clarification – Malachi – 2014-01-17T00:41:37.210

Clever rule-bending :) – chbaker0 – 2014-01-17T05:17:56.510

+1, but as written you have 75 chars including whitespace. And n=1;While[1==1,Spacer[70 Sin[n Pi/32]+70]~Print~"|";Pause@.05;n++] is 66 chars. – Ajasja – 2014-01-17T10:13:42.900

1And here is a 58 char version Do[Spacer[70*Sin[n*Pi/32]+70]~Print~"|";Pause@.05,{n,18!}] – Ajasja – 2014-01-17T10:22:59.010

1Im not a Mathematica user, but i think you can change 1 == 1 to 0 < 1 to decrease 1 char. – CCP – 2014-03-24T23:27:06.517

@CCP 2 Yes, you are correct! Thanks. – DavidC – 2014-03-25T01:50:21.733

11

Perl, 48 (68)

GNU sleep version: 48

print$"x(25+20*sin).'|
';$_+=.1;`sleep .05`;do$0

Cross platform: 68

use Time::HiRes"sleep";print$"x(25+20*sin).'|
';$_+=.1;sleep.05;do$0

Removed the use of Time::HiRes module by using shell sleep function. Shortened increment as per Ruby example. Shortened using $" and $0 seeing hints from Primo's work Thanks for hints Primo.

KevinColyer

Posted 2014-01-16T17:48:59.753

Reputation: 171

I saved this as a file test.pl and ran perl ./test.pl, however the waiting time does not match the specification. Also, the amplitude of the wave is too small. (This amplitude refers to the length between the peak and the equilibrium position.) – user12205 – 2014-01-16T21:42:37.460

I guess if I changed the increment from .105 to .1 I would beat ruby at 56 chars! – KevinColyer – 2014-01-16T22:50:49.247

@primo - my shell sleep does do times shorter than 1 second... – KevinColyer – 2014-01-17T08:32:44.423

man sleepunsigned int sleep(unsigned int seconds);. It won't error, but the actual sleep interval is zero. Some suggestions to make yours shorter: change $d to $_, and then use (25+20*sin), and change the \n for a literal newline. – primo – 2014-01-17T08:45:10.607

2@primo man 1 sleep on a GNU/Linux bash shell tells us that Unlike most implementations that require NUMBER be an integer, here NUMBER may be an arbitrary floating point number. – user12205 – 2014-01-17T08:58:06.660

@ace good to know. – primo – 2014-01-17T09:07:02.333

I left the GNU sleep version running on my PC over the weekend. I thought you might like to know that it leaked 5GB memory – user1207217 – 2014-01-20T14:01:02.043

Shocking news!!! I guess the do$0 is the culprit. But it saves a byte instead of putting it in a block and calling redo at the end of the block... – KevinColyer – 2014-02-02T20:23:26.107

11

Perl - 64 (or 60) bytes

The following uses a Windows-specific shell command:

`sleep/m50`,print$"x(20.5-$_*(32-abs)/12.8),'|
'for-32..31;do$0

The following uses a GNU/Linux-specific shell command:

`sleep .05`,print$"x(20.5-$_*(32-abs)/12.8),'|
'for-32..31;do$0

Both at 64 bytes.

  • Period is 64.
  • Maximum amplitude is exactly 20.
  • The curve is perfectly symmetric.
  • Every period is identical.
                    |
                      |
                         |
                           |
                             |
                               |
                                |
                                  |
                                   |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                      |
                    |
                  |
               |
             |
           |
         |
        |
      |
     |
    |
   |
  |
 |
 |
|
|
|
|
|
 |
 |
  |
   |
    |
     |
      |
        |
         |
           |
             |
               |
                  |
                    |
                      |
                         |
                           |
                             |
                               |
                                |
                                  |
                                   |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                      |
                    |
                  |
               |
             |
           |
         |
        |
      |
     |
    |
   |
  |
 |
 |
|
|
|
|
|
 |
 |
  |
   |
    |
     |
      |
        |
         |
           |
             |
               |
                  |
                    |

Note that this isn't exactly a sinusoidal wave, but rather a quadratic interpolation. Plotted against an actual sin:

At the granularity required, these are visually indistinguishable.

If the aesthetics aren't so important, I offer a 60 byte alternative, with period length 62, maximum amplitude of ~20.02, and slight asymmetries:

`sleep/m50`,print$"x(20-$_*(31-abs)/12),'|
'for-31..30;do$0

primo

Posted 2014-01-16T17:48:59.753

Reputation: 30 891

This isn't a sinusoidal wave; it is simply parabolas (if I read your code right). (If you can represent this with some sinusoidal wave, I'd love to see the function). – Justin – 2014-01-21T04:01:44.230

Sine is a formula, if you replicate the formula it is still a Sinusoidal wave. and this is probably a variant of Sine in some fashion. – Malachi – 2014-02-10T15:13:47.277

8

Ruby 56

i=0
loop{puts" "*(20*Math.sin(i+=0.1)+20)+?|;sleep 0.05}

daniero

Posted 2014-01-16T17:48:59.753

Reputation: 17 193

Is replacing puts with p allowed? – Slicedpan – 2014-01-17T10:12:45.557

1@Slicedpan I think I won't, since this is a challenge to draw something. p will add double quotes around around each line and alter the "drawing". – daniero – 2014-01-17T15:37:32.300

7

Befunge 98 - 103 100

:1g:02p' \k:02gk,'|,a,$ff*:*8*kz1+:'<\`*
468:<=?ABDEFGGGHGGGFEDBA?=<:86420.,+)'&$#"!!! !!!"#$&')+,.02

Cheers for a program that does this, in a language without trigonometric capabilities; the first program in fact. The second line is simply data; the character corresponding with the ascii value of the sin, added to a space character.

EDIT: I saved 3 chars by not subtracting the space away; the sinusoid is translated 32 units to the right (which is valid).

Befunge also does not have a sleep command, or something similar. It would be nice to find a fingerprint, but I couldn't find one, so ff*:*8* pushes 8*225**2 (405000) and kz runs a noop that many times (well, that many times + 1). On windows command line with pyfunge, this turns out to be about 50 milliseconds, so I say I'm good. Note: if anyone knows a good fingerprint for this, please let me know.

The last part of the code simply checks if the counter (for the data line) is past the data, if it is, the the counter is reset to 0.

I used this to generate the data.


Taylor Series

Although this version is 105 chars, I just had to include it:

:::f`!4*jf2*-:::*:*9*\:*aa*:*:01p*-01g9*/a2*+\$\f`!4*j01-*b2*+:01p' \k:01gk,$'|,a,ff*:*8*kz1+:f3*`!3*j$e-

I was trying to shorten my program, and decided to look at the taylor series for cosine (sine is harder to calculate). I changed x to pi * x / 30 to match the period requested here, then multiplied by 20 to match the amplitude. I made some simplifications (adjusted factors for canceling, without changing the value of the function by much). Then I implemented it. Sadly, it is not a shorter implementation.

:f`!4*jf2*-

checks whether the values of the taylor series are getting inaccurate (about x = 15). If they are, then I compute the taylor series for x - 30 instead of x.

:::*:*9*\:*aa*:*:01p*-01g9*/a2*+

is my implementation of the taylor series at x = 0, when x is the value on the stack.

\$\f`!4*j01-* 

negates the value of the taylor series if the taylor series needed adjustment.

b2*+

make the cosine wave positive; otherwise, the printing would not work.

:01p' \k:01gk,$'|,a,

prints the wave

ff*:*8*kz1+

makeshift wait for 50 milliseconds, then increment x

:f3*`!3*j$e-

If x is greater than 45, change it to -14 (again, taylor series error adjustment).

Justin

Posted 2014-01-16T17:48:59.753

Reputation: 19 757

This is exactly the kind of answer I'm looking forward to, hope you can golf it down :) – user12205 – 2014-01-17T08:08:29.310

1There! I successfully decreased the code length by -5 chars! And there is still room for improvement! – Justin – 2014-01-19T09:42:06.810

@Quincunx my perl solution also does not use any built in trig functions ;) – primo – 2014-01-21T03:05:15.493

6

Python, 108,93,90,89,88

import math,time
a=0
while 1:print" "*int(20+20*math.sin(a))+"|";time.sleep(.05);a+=.1

Now with infinite scrolling :)

Edit: ok, 90. Enough?

Edit:Edit: no, 89.

Edit:Edit:Edit: 88 thanks to boothby.

Gabriele D'Antona

Posted 2014-01-16T17:48:59.753

Reputation: 1 336

Sorry if I haven't made the question clear - your program should not terminate and should continuously scroll down the wave (except until SIGINT) – user12205 – 2014-01-16T19:26:42.520

1a=0. -> a=0 gets you to 88 – boothby – 2014-01-16T23:03:34.377

5

PHP, 59 characters

<?for(;;usleep(5e4))echo str_pad('',22+20*sin($a+=.1)).~ƒõ;

Alex Barrett

Posted 2014-01-16T17:48:59.753

Reputation: 161

1You can save yourself some bytes by using echo ...; in place of fwrite(STDOUT,...);. – primo – 2014-01-17T06:08:25.920

That makes sense when calling from the command line anyway. 10 characters saved - thanks primo. – Alex Barrett – 2014-01-17T10:02:48.050

158: <?for(;;)echo~str_pad(ƒõ,22+20*sin($a+=.1),ß,usleep(5e4)); – primo – 2014-01-17T10:56:16.897

Very nice. I won't edit my answer with those changes, you should post as your own. – Alex Barrett – 2014-01-17T11:05:56.723

Is this verified to work? It doesn't work on http://ideone.com/6gmtfl , nor does it work on my computer. (Although it does print a sine wave with the error message)

– user12205 – 2014-01-17T11:12:53.960

1@ace it needs to be saved with an ansi encoding. ideone automatically converts everything to utf-8, which breaks. ~ƒõ is just shorthand for "|\n". – primo – 2014-01-17T11:17:12.370

@AlexBarrett the difference isn't significant enough to warrent a separate answer. I just like to see PHP do well. If you prefer, you can add it to your own as "a 58 byte variant suggested by primo" or some such ;) – primo – 2014-01-17T11:26:10.827

4

C64 BASIC, 64 PETSCII chars

enter image description here

On a PAL C64, For i=0 to 2:next i cycles for approx. 0,05 seconds, so the delay time is respected.

Gabriele D'Antona

Posted 2014-01-16T17:48:59.753

Reputation: 1 336

3

C - 86+3 characters

Thanks shiona and Josh for the edit

i;main(j){for(;j++<21+sin(i*.1)*20;)putchar(32);puts("|");usleep(50000);i++;main(1);}

i;main(j){for(j=0;j++<20+sin(i/10.)*20;)putchar(32);puts("|");usleep(50000);i++;main();}

float i;main(j){for(j=0;j++<20+sin(i)*20;)putchar(32);puts("|");usleep(50000);i+=.1;main();}

Compiled with the -lm flag, I assume I need to add 3 chars

user12205

Posted 2014-01-16T17:48:59.753

Reputation: 8 752

1Would it work if you made i an int and just divided it by 10.0 (or 9.9 to save a char?) within the call to sin()? i;main(j){for(j=0;j++<20+sin(i/10.0)*20;)putchar(32);puts("|");usleep(50000);i++;main();} – shiona – 2014-01-16T18:24:10.473

You can bring the size down to 76 characters or so by using printf() to replace the for loop: printf("%*s\n",(int)(21+sin(i++/10.)*20),"|") – treamur – 2014-01-16T21:28:44.813

1Hmm... I would feel really guilty if I use this idea in my answer, especially when this is my own question... Would you consider posting an answer yourself? – user12205 – 2014-01-16T21:36:53.040

Ok, will do. Thanks. :) – treamur – 2014-01-16T21:38:08.040

1You can shave off two more characters if you remove the j=0: i;main(j){for(;j++<21+sin(i/10.)*20;)putchar(32);puts("|");usleep(50000);i++;main(1);}. This relies on the assumption that the program is called with 0 arguments. – Josh – 2014-01-16T22:43:06.443

Most conversations regarding interpreter/compiler flags have resolved with each flag used costing a byte, but the - before being free. – primo – 2014-01-17T11:28:23.147

3

Javascript 88 76 78 characters

setInterval('console.log(Array(Math.sin(i++/10)*20+21|0).join(" ")+"|")',i=50)

Based on Kendall Frey's code.

joeytje50

Posted 2014-01-16T17:48:59.753

Reputation: 573

You never initialize i, so it prints a straight line instead of a wave. – gilly3 – 2014-01-16T22:37:51.003

My mistake... It probably worked because I had ran Kendall's script already in my console, so i was initialised already for me. – joeytje50 – 2014-01-16T22:41:00.213

3

Ti-Basic, 33 bytes

While 1:Output(8,int(7sin(X)+8),"!":Disp "":π/30+X→X:End

The following caveats exist:

  1. Due to screen limitation of 16x8, this sine wave only has an amplitude of 7 (period of 60 is still maintained)

  2. Due to lack of an easy way to access the | char, ! is used instead

  3. Due to lack of an accurate system timer, the delay is not implemented. However, run speed appears approximately correct.

Mike Clark

Posted 2014-01-16T17:48:59.753

Reputation: 171

1Heh, since TI-BASIC is counted in one-/two- byte tokens, this is actually 33 bytes (not "56 chars"), so it actually should have won the challenge! – M. I. Wright – 2015-06-15T04:12:30.407

Except for the amplitude thing... – lirtosiast – 2015-06-16T04:01:16.757

Well, yes, but going by bytes it's fine. – M. I. Wright – 2015-06-16T04:46:28.357

2

JavaScript - 88

setInterval(function(){console.log(Array(Math.sin(i++/10)*20+21|0).join(" ")+"|")},i=50)

I'm sure someone can come up with something that's actually clever.

Kendall Frey

Posted 2014-01-16T17:48:59.753

Reputation: 2 384

2

J - 103,58,57,54

Thanks to awesome guys from IRC

(0.1&+[6!:3@]&0.05[2:1!:2~' |'#~1,~[:<.20*1+1&o.)^:_]0

In words from right to left it reads: starting from 0 infinite times do: sin, add 1 ,multiply by 20, floor, append 1 (so it becomes array of 2 elements), copy two bytes ' |' correspondingly, print it, wait 0.05s and add 0.1

Instead of infinite loop we can use recursion, it would save 2 characters, but will also produce a stack error after some number of iterations

($:+&0.1[6!:3@]&0.05[2:1!:2~' |'#~1,~[:<.20*1+1&o.)0  

Where $: is a recursive call.

swish

Posted 2014-01-16T17:48:59.753

Reputation: 7 484

Would you mind adding a little explanation, so that people unfamiliar with the J syntax (like me) can also understand your answer? – user12205 – 2014-01-17T08:09:47.677

It's possible to shorten this to 50 characters by fussing about with the train's structure: (+2*(%20)6!:3@[2:1!:2~' |'#~1,~[:<.20*1+1&o.)^:_]0. The recursion version only saves 1 char this time $:@(+2*(%20)6!:3@[2:1!:2~' |'#~1,~[:<.20*1+1&o.)0 though it appears to last longer before bottoming out. – algorithmshark – 2014-02-15T08:28:56.960

2

Haskell - 75

main=putStr$concat["|\n"++take(floor$20+20*sin x)(repeat ' ')|x<-[0,0.1..]]

Unfortunately, I couldn't get the program to pause 50 ms without doubling my char count, so it just floods the console, but it does produce the sine wave.


Here's the full code with pausing (138 chars with newlines):

import GHC.Conc
import Control.Monad
main=mapM_(\a->putStr a>>threadDelay 50000)(["|\n"++take(floor$20+20*sin x)(repeat ' ')|x<-[0,0.1..]])

Zaq

Posted 2014-01-16T17:48:59.753

Reputation: 1 525

2Pausing was one of the requirements. Can you also post the code with the pause? – Justin – 2014-01-16T23:03:27.623

Okay, I posted it. I wish Haskell let you pause code without imports. – Zaq – 2014-01-16T23:29:04.510

By amplitude I mean the peak amplitude, i.e. twice the amplitude of your current program. You may wish to change it to 20+20*sin x instead to qualify. – user12205 – 2014-01-17T13:52:23.323

Oh, sure. I guess I misinterpreted that part of the question. – Zaq – 2014-01-18T02:56:10.600

2

fugly Javascript - 77

i=setInterval("console.log(Array(Math.sin(i+=.1)*20+20|0).join(' ')+'|')",50)

and if we do it in Firefox - 73

i=setInterval("console.log(' '.repeat(Math.sin(i+=.1)*20+20|0)+'|');",50)

and if we're nasty - 67

i=setInterval("throw(' '.repeat(Math.sin(i+=.1)*20+20|0)+'|');",50)

eithed

Posted 2014-01-16T17:48:59.753

Reputation: 1 229

2

Perl 6: 46 chars

sleep .05*say ' 'x(25+20*.sin),'|'for 0,.1...*

Create an infinite lazy Range using 0,0.1 ... *, loop over that. say returns Bool::True which numifies as 1 in multiplication, this way I can keep it in a single statement.

Ayiko

Posted 2014-01-16T17:48:59.753

Reputation: 519

I can see why sleep and .05 have to be separated. But I wonder if the space between say and ' ' is mandatory? – Matthias – 2014-01-19T22:35:07.540

Yes :s It gives "2 terms in a row" error for say' ' One can use say(' ') but that's 1 char extra in this case... – Ayiko – 2014-01-20T18:07:03.460

1@Matthias: In Perl 6, listops either have to not take arguments, have a space after them, or use parenthesis. It's not a language designed for code golf, unlike Perl 5 (but it contains many nice builtin features, so it's usable). – Konrad Borowski – 2014-01-22T16:43:28.360

@xfix Thank you for the explanation. I like the language, but I did not look into it thoroughly yet, because I still cannot use it in a work project yet. However, I always plan to write some Perl 6 scripts. @ Ayiko, I appreciate your Perl 6 posts :-) – Matthias – 2014-01-22T23:16:56.507

1

Python 3, 103

Stupid frikk'n imports...

import time,math
t=0
while 1:t+=(.05+t<time.clock())and(print(' '*int(20+20*math.cos(t*1.9))+'|')or.05)

Rather than "sleep", this implementation grinds at the cpu because python makes it easier to get a floating-point cpu clock than wall clock. This approach won't beat friol's, but it's fun so I'm leaving it up.

boothby

Posted 2014-01-16T17:48:59.753

Reputation: 9 038

1

C#

The Magic Line [91] Characters

for(var i=0d;;Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|'))Thread.Sleep(50);

Working Program Below. [148] Characters

namespace System{class P{static void Main(){for(var i=0d;;Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|'))Threading.Thread.Sleep(50);}}}

John ClearZ

Posted 2014-01-16T17:48:59.753

Reputation: 131

Sorry if I haven't made the question clear - your program should not terminate and should continuously scroll down the wave (except until SIGINT). Also, please add a character count. – user12205 – 2014-01-16T20:08:06.933

Sorry forgot about that bit. Fixed now. – John ClearZ – 2014-01-16T20:24:25.900

I think you can lose "Thread.Sleep"s and change "float" with var :) 117 chars. -- Sorry didn't see the wait time.. 133 chars now.

using System;class P{static void Main(){for(var i=0d;;Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|'))Thread.Sleep(50);}} – Medeni Baykal – 2014-01-16T21:17:12.427

Yes I thought about changing it to var but wasn't sure about making changes after I got a +1. The reason I used Fully Qualified names is Thread uses the System.Threading namespace so it would have to be using System;using System.Threading;class P{static void Main(){for(var i=0d;;Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|'))Thread.Sleep(5‌​0);}} This ends up longer I think – John ClearZ – 2014-01-16T22:32:42.570

Made the change by not using FQN's for Console and Math it saves 1 char. Also using var saves another 2 chars :-} – John ClearZ – 2014-01-16T22:44:09.753

I'm just upvoting answers that I have verified to be correct. Feel free to shorten your code as long as the output is the same :) – user12205 – 2014-01-16T22:59:29.780

I counted 150 characters for your working program. It's possible to shrink it to 148 by sticking the whole thing into the System namespace: namespace System{class P{static void Main(){for(var i=0d;;Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|'))Threading.Thread.Sleep(50);}}} see http://codegolf.stackexchange.com/a/184/4163

– Bob – 2014-01-17T02:02:19.913

Ha nice one Bob. I wouldn't have thought about that. – John ClearZ – 2014-01-17T03:35:47.183

1I can't get it to compile in VS2010 with Threading.Thread.Sleep(50) am I doing something wrong? – Malachi – 2014-01-17T15:57:22.330

1I was able to get it to run, but I had to add some Brackets and Semi-colons and it doesn't look the same every period – Malachi – 2014-01-17T16:17:55.933

Compilation failed on gmcs also after direct copy-and-paste of the sourcecode due to Unexpected character. I retyped the sourcecode on a new file and it works again. I guess there is some non-printable character hidden in this code, leading to the compilation error. – user12205 – 2014-01-17T16:30:57.070

There must have been a hidden character added when I pasted the code here. It is fixed not. Also Malachi there is nothing wrong with the number of ')' and '}' characters and their placement. The only thing that is wrong is your understanding that you can place a statement inside the for loop – John ClearZ – 2014-01-20T14:56:36.743

1

Scala, 92,89,87

def f(i:Int){println(" "*(20+20*math.sin(i*.1)).toInt+"|");Thread sleep 50;f(i+1)};f(1)

ValarDohaeris

Posted 2014-01-16T17:48:59.753

Reputation: 231

(20+20*math.sin(i*.1)) reduces it by 1 char, assuming this is valid syntax (I have no experience with Scala) – user12205 – 2014-01-16T21:14:54.220

Thanks, but I have just discovered that myself :) – ValarDohaeris – 2014-01-16T21:20:22.303

1

C#

[152] Characters

namespace System{class P{static void Main(){for(var i=0d;;){Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|');Threading.Thread.Sleep(50);}}}}

I could not get the Existing C# answer to Run and I couldn't downvote because I don't have enough Reputation

it was missing a couple of { and missing a ) after the For Loop Declaration.

I figure that the variance in the look of the wave when it is run is because of the way we are trying to display this wave.


if we aren't counting the Namespace and the Method Declaration then it would be [104] characters for the working version

for(var i=0d;;){Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|');Threading.Thread.Sleep(50);}

Malachi

Posted 2014-01-16T17:48:59.753

Reputation: 240

The other C# answer works on gmcs. It fails to compile at first, but I think it is because there is some non-printable character in the source code. After typing it again on an empty file, the compilation is successful. – user12205 – 2014-01-17T16:38:14.817

Compilers can be picky, huh? – Malachi – 2014-01-17T16:49:00.870

1

VB [236][178]

not sure how you would count the tabs, I just took the count from Notepadd++ before I pasted here. newlines are mandatory, probably why no one likes using it for code golfing.

Module Module1
Sub Main()
Dim i
While True
Console.WriteLine("{0:" & (40 + 20 * Math.Sin(i = i + 0.1)) & "}", "|")
Threading.Thread.Sleep(50)
End While
End Sub
End Module

Malachi

Posted 2014-01-16T17:48:59.753

Reputation: 240

1

Bash+bc (to do the math), 80

$ for((;;i++)){ printf "%$(bc -l<<<"a=20*s($i/10);scale=0;a/1+20")s|
";sleep .05;}
                |
                 |
                   |
                     |
                       |
                         |
                           |
                            |
                              |
                               |
                                |
                                 |
                                  |
                                   |
                                   |
                                   |
                                   |
                                   |
                                   |

Digital Trauma

Posted 2014-01-16T17:48:59.753

Reputation: 64 644

1

Julia - 68

Edit: thanks to M L and ace.

i=0;while 0<1;println(" "^int(20sin(.1i)+20)*"|");i+=1;sleep(.05)end

Well, it can not compete vs APL, but here's my attempt.

Output:

                    |
                      |
                        |
                          |
                            |
                              |
                               |
                                 |
                                  |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                   |
                                  |
                                |
                              |
                             |
                           |
                         |
                       |
                     |
                   |
                 |
               |
             |
           |
         |
        |
      |
     |
    |
   |
  |
 |
|
|
|
|
|
 |
 |
  |
   |
     |
      |
       |
         |
           |
             |
              |
                |
                  |
                    |
                      |
                        |
                          |
                            |
                              |
                                |
                                 |
                                   |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                   |
                                 |
                                |
                              |
                            |
                          |
                        |
                      |
                    |
                  |
                 |
               |
             |
           |
         |
       |
      |
     |
   |
  |
  |
 |
|
|
|
|
|
 |
  |
  |
    |
     |
      |
        |
         |
           |
             |
               |
                 |
                   |
                     |
                       |
                         |
                           |
                            |
                              |
                                |
                                 |
                                   |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                  |
                                 |
                               |
                              |
                            |
                          |
                        |
                      |
                    |
                  |
                |
              |
            |
           |
         |
       |
      |
    |
   |
  |
 |
 |
|
|
|
|
|
 |
  |
   |
    |
     |
      |
        |
          |
           |
             |
               |
                 |
                   |
                     |
                       |
                         |
                           |
                             |
                              |
                                |
                                  |
                                   |
                                    |
                                     |
                                      |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                  |
                                 |
                               |
                             |
                            |
                          |
                        |
                      |
                    |
                  |
                |
              |
            |
          |
         |
       |
      |
    |
   |
  |
 |
 |
|
|
|
|
 |
 |
  |
   |
    |
     |
       |
        |
          |
            |
             |
               |
                 |
                   |
                     |
                       |
                         |
                           |
                             |
                               |
                                |
                                  |
                                   |
                                    |
                                      |
                                      |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                      |
                                      |
                                     |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                       |
                     |
                   |

CCP

Posted 2014-01-16T17:48:59.753

Reputation: 632

Cut it down to 68 characters: i=0;while 0<1;println(" "^int(20sin(.1i)+20)*"|");i+=1;sleep(.05)end———sin(i/10)*20 is equal to 20sin(.1i) – M L – 2015-06-20T02:56:11.773

I don't know Julia, but could you use a for loop iterating over all the natural numbers instead? – lirtosiast – 2015-06-22T03:31:23.563

1I don't know Julia, but is it possible to use .05 instead of 0.05 in sleep? – user12205 – 2014-03-25T03:13:22.313

Actually yes! Thanks – CCP – 2014-03-25T19:44:26.067

1

TI-BASIC, 30 bytes

Small size improvement over the other answer, at the cost of some accuracy. Note that TI-Basic technically has the | character, but you have to transfer it via computer or use an assembly program to access it.

While 1
Output(8,int(8+7sin(Ans)),":
Disp "
.03π+Ans
End

M. I. Wright

Posted 2014-01-16T17:48:59.753

Reputation: 849

Woah, did not see how old this challenge was! Was going to try to golf this more (which is definitely possible) but it's really not worth it... – M. I. Wright – 2015-06-15T04:11:28.303

By the way, .03π can be .1, which is still within the required interval. – lirtosiast – 2015-06-16T03:59:03.990

Nice catch, thanks! Do you see any way I could golf the output command? Also, since I have a CSE, I could get this to the right amplitude (26-char screen) at the cost of a few bytes. – M. I. Wright – 2015-06-16T04:48:38.697

No, the output command looks fine--too bad the Disp needs a quote. The amplitude should be 20 chars, actually, making the screen width requirement 39. So it would only work on the graph screen, and there's no short way of doing that. – lirtosiast – 2015-06-16T05:22:22.383

1

MATLAB, 81 bytes

t=0;while(fprintf('%s\n',i))i=[];t=t+1;i(fix(21+20*sind(t*6)))='|';pause(.05);end

I abused the fact that i is always initialized in MATLAB, which meant that I could put the fprintf in the while statement without initializing i first. This does mean the program first outputs an empty line, but I think this is not forbidden in the spec.

Furthermore, it abuses the fact that Matlab will ignore most ASCII control characters, printing a space instead of NULL (also for the first empty line).

Sanchises

Posted 2014-01-16T17:48:59.753

Reputation: 8 530

"I abused the fact that i is always initialized in MATLAB, which meant that I could put the fprintf in the while statement without initializing i first." Really clever! +1! – Stewie Griffin – 2016-01-20T21:20:46.130

0

SmileBASIC, 44 bytes

@L
A=A+.1?" "*(COS(A)*20+20);"|
WAIT 3GOTO@L

12Me21

Posted 2014-01-16T17:48:59.753

Reputation: 6 110

0

PowerShell, 57 bytes

for(;;sleep -m 50){' '*(20*[math]::Sin(($i+=.1))+20)+'|'}

Try it online!

mazzy

Posted 2014-01-16T17:48:59.753

Reputation: 4 832

0

TI-BASIC, 37

Executed from a TI-84 calculator

:While 1:DrawInv 2.9sin(X:ClrDraw:End
  • Peak Amplitude = 20
  • Period = 62
  • Pause between lines 50-60 ms (very close as there is no built-in clock)

Timtech

Posted 2014-01-16T17:48:59.753

Reputation: 12 038

5OP: this is an ascii-art problem – MrZander – 2014-01-17T00:13:12.357

@MrZander I'm aware of this (it only uses symbols newline, space, and |) – Timtech – 2014-01-17T00:35:27.927

1almost all of the programming language answers use a predefined function for Sine, so I don't see how this would be against the rules. as this uses the predefined function for the language it is written in just the same as say Javascript – Malachi – 2014-01-17T00:44:24.033

1The problem @MrZander is trying to bring up here is that you're not doing this with ASCII characters, but by drawing a graph. That's against the rules. – joeytje50 – 2014-01-17T01:14:17.570

1No, it draws it with ASCII. – Timtech – 2014-01-17T01:29:22.810

5

No, DrawInv is a graphing feature of the TI-84, so this is just like using Mathematica to plot a sine wave. http://tibasicdev.wikidot.com/drawinv Also, all TI-84s have RTCs.

– Kevin Chen – 2014-01-17T04:56:38.580

1I do not consider this to be a valid answer (since amplitude <20) – user12205 – 2014-01-17T08:12:38.507

@ace It's fixed. – Timtech – 2014-01-17T15:21:19.887

7I agree with @Kevin Chen that this is essentially just like using Mathematica to plot a sine wave. So, I still do not consider this to be a valid answer. Also, according to the picture in the link given by Kevin, I do not consider this to be ascii art. I think this is just some low resolution bitmap, so this answer does not qualify. – user12205 – 2014-01-17T16:42:20.120

0

F# - 90 79 77 76

Here's a solution using recursion

let rec f x=printfn"%*c"(int(20.*sin x)+21)'|';Thread.Sleep 50;f(x+0.1)
f 0.

It could probably be improved further.

p.s.w.g

Posted 2014-01-16T17:48:59.753

Reputation: 573

Without knowing anything about F#, I'm assuming that Thread.Sleep expects a value in ms, so you can get rid of one of the 0's and do Thread.Sleep 50. :) – ValarDohaeris – 2014-01-17T00:49:29.037

@ValarDohaeris You're right. I misread the requirements. – p.s.w.g – 2014-01-17T00:54:00.540

0

AutoHotkey 176

SetKeyDelay,-1
run Notepad.exe
WinWaitActive, ahk_class Notepad
p:=0
loop
{
sleep 50
p+=Mod(Floor(A_index/40),2)?-1:1,t:=""
loop % p
t .= " "
sendinput % t "|`n"
}
esc::Exitapp

Run the script . It opens Notepad and prints the characters. Press Esc anytime to exit.

Avi

Posted 2014-01-16T17:48:59.753

Reputation: 261

0

Clojure, 121

Short version:

(loop[a 0](println(clojure.string/join(repeat(int(+ 20 (* 20 (Math/sin a)))) " ")) \|)(Thread/sleep 50)(recur(+ a 0.1)))

Pretty version:

(loop [a 0]
  (println (clojure.string/join (repeat (int (+ 20 (* 20 (Math/sin a)))) " ")) \|)    
  (Thread/sleep 50)
  (recur(+ a 0.1)))

Period is 64.

Type this into lein repl or save in file sin.clj and run with lein exec sin.clj (requires lein-exec plugin).

ctrlrsf

Posted 2014-01-16T17:48:59.753

Reputation: 1

0

GTB, 14

Executed from a TI-84 calculator

[i;2.9sin(Xc;]

Amplitude = 20, Period = 62, Pause = ~50

Timtech

Posted 2014-01-16T17:48:59.753

Reputation: 12 038

Since this is basically the same as your other answer, I consider this to be invalid as well.

– user12205 – 2015-06-14T22:33:29.540

0

Groovy 87 Chars

Okay, now for a serious answer that actually follows the guidelines

def x=0;while(true){println ' '*(20*Math.sin(x)+20)+'|';x+=0.1;Thread.sleep(50)}

Mike Clark

Posted 2014-01-16T17:48:59.753

Reputation: 171

2Do you think a suitable decimal approximation for Math.PI/30 can save you a few chars? – user12205 – 2014-01-17T16:53:13.793

0

CJam, 42 bytes

CJam is a bit younger than this challenge, but since this submission doesn't beat APL anyway, I don't see a problem with that.

es{es1$m50>{500d/ms21*K+S41*\i'|tN+oes}*}h

This won't work in the online interpreter, so you'll have to use the Java one.

The basic idea is to keep a timestamp on the stack, and whenever 50 ms have passed since the last timestamp, a new line is printed (where the sine is computed from that last time), and a new timestamp left on the stack.

Martin Ender

Posted 2014-01-16T17:48:59.753

Reputation: 184 808

0

Pascal: 99 characters

uses Crt;var i:Real;begin
repeat
Writeln('|':Round(Sin(i)*20+21));i:=i+0.1;Delay(500)until 0=1;end.

Another task where Pascal's output formatting comes handy and everything else is pain.

manatwork

Posted 2014-01-16T17:48:59.753

Reputation: 17 865

0

Julia, 60 chars

Unlike CCP’s solution, mine uses a recursive function:

a(n)=(print(" "^int(20sin(.1n)+20)*"|\n");sleep(.05);a(n+1))

Example:

julia> a(1)
                      |
                        |
                          |
                            |
                              |
                               |
                                 |
                                  |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                   |
                                  |
                                |
                              |
                             |

M L

Posted 2014-01-16T17:48:59.753

Reputation: 2 865