Computer Science Canada

Exercise: Beeping!

Author:  wtd [ Tue May 06, 2008 10:34 pm ]
Post subject:  Exercise: Beeping!

In the language of your choosing, write a program that gets a line of input from the user, then print it character by character. After each character is printed make the computer beep, then wait one second.

Please state the language you're using.

Author:  HeavenAgain [ Tue May 06, 2008 10:45 pm ]
Post subject:  Re: Exercise: Beeping!

using java, not sure about which beeping sound...
Java:
import java.awt.*;
import java.util.*;
public class Beeping {
  public static void main(String args[]) {
    String line = new Scanner(System.in).nextLine();
    for (int i = 0 ; i < line.length(); i++){
      System.out.println(line.charAt(i));
      Toolkit.getDefaultToolkit().beep();
      Thread.sleep(1000);
    }
  }
}

Author:  Zampano [ Tue May 06, 2008 10:50 pm ]
Post subject:  Re: Exercise: Beeping!

code:
var word: string
get word
for c: 1 .. length (word)
    put word (c)
end for
Music.Sound (400,200)
Music.SoundOff
delay (1000)

Can I take this opportunity to ask something? In these for loops, is the value c is to be compared to determined once at the initiation of the for loop, or is it done each time the loop cycles? If it was done in C++:
code:
for (int c = 0; c != word.size (); c++)

You would do well to define a const to hold word.size () because you need to call the member method size each time you want to check the condition, creating a redundancy. In Turing, is the value represented by word.size () here created once or many times?

Author:  HeavenAgain [ Tue May 06, 2008 10:57 pm ]
Post subject:  RE:Exercise: Beeping!

Quote:
In these for loops, is the value c is to be compared to determined once at the initiation of the for loop, or is it done each time the loop cycles? If it was done in C++:
if you are asking about the order of the for loop structure, it goes something like this,
initialize first, then check, if true then run, and then do the 3rd block (normally increment/decrement), then check, then run, if false then stop and move on.

and yes, it is better if you use a variable to keep track of length, instead of having to call to another method/function every time, and i think it goes the same for turing as well Rolling Eyes

Quote:
After each character is printed make the computer beep, then wait one second.
thats probably the tricky part..... Crying or Very sad

Author:  Zampano [ Tue May 06, 2008 11:13 pm ]
Post subject:  Re: Exercise: Beeping!

Thank heavens and thank you HeavenAgain for the help. I guess I ought to revise my answer to accomodate for my misunderstanding, right?
code:
var word:string
get word
for c:1..length (word)
    put word(c)
    Music.Sound(400,200)
    Music.SoundOff
    delay (1000)
end for

But since Turing finds the value of length (word) right at the beginning and only at that time, do I need to use that const? I think not.

Author:  wtd [ Tue May 06, 2008 11:53 pm ]
Post subject:  RE:Exercise: Beeping!

Io

code:
outputWithBeepingAndDelay := method(msg, delay,
    msg foreach(c,
        (c asCharacter .. "\a") print
        System sleep(delay)
    )
    "" println
)

userInput := File standardInput readLine
delay := 1

outputWithBeepingAndDelay(userInput, delay)

Author:  rdrake [ Wed May 07, 2008 1:38 am ]
Post subject:  Re: Exercise: Beeping!

This probably counts as more than one line, but here's Ruby:
Ruby:
gets.chomp; scan(/./m).each do |c| print c + "\a"; sleep(1) end


EDIT: What the hell, here's Python too:
Python:
import time
str = raw_input("")
for c in str:
     print c + "\a"
     time.sleep(1)

Author:  btiffin [ Wed May 07, 2008 2:06 am ]
Post subject:  Re: Exercise: Beeping!

REBOL using console beep
code:
REBOL []

charbeep: func [str] [foreach ch str [prin ch prin #"^G" wait 00:00:01]]
charbeep ask "? "

; As a gui
view layout [field [charbeep get-face face] button "Close" [unview/all halt]]


REBOL using soundcard
code:
REBOL []
; Generate a ping waveform as a binary value:
ping: #{}
for amplitude 200 1 -1 [
    for phase 1 360 16 [
        val: 128 + to-integer 127 * sine phase
        val: amplitude * val / 200
        append ping to-char val
    ]
]
; Set up the sound sample parameters
sample: make sound [
    rate: 44100 / 2
    channels: 1
    bits: 8
    volume: 0.5
    data: #{}
]
append sample/data ping
beep: does [
    sound-port: open sound://
    insert sound-port sample
    wait sound-port
    close sound-port
]

; The task at hand, delay as function arg this time
charbeep: func [str delay] [foreach ch str [prin ch beep wait delay]]
charbeep ask "? " 00:00:01

; As a go function gui
go: does [view layout [field [charbeep get-face face 00:00:01] button "Close" [unview/all halt]]] go

Author:  michaelp [ Wed May 07, 2008 4:14 pm ]
Post subject:  RE:Exercise: Beeping!

C++:
code:
#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main()
{
    cout << "Please enter a word: ";
    string word;
    cin >> word;
    for( int i = 0; i < word.length(); i++ )
    {
        cout << word[i] << "\a" << endl;
    }

    return 0;
}


Without a new letter on every line:

code:
#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main()
{
    cout << "Please enter a word: ";
    string word;
    cin >> word;
    for( int i = 0; i < word.length(); i++ )
    {
        cout << word[i] << "\a";
    }

    return 0;
}

Author:  md [ Wed May 07, 2008 4:49 pm ]
Post subject:  Re: RE:Exercise: Beeping!

michaelp @ 2008-05-07, 4:14 pm wrote:
C++:
code:
#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main()
{
    cout << "Please enter a word: ";
    string word;
    cin >> word;
    for( int i = 0; i < word.length(); i++ )
    {
        cout << word[i] << "\a" << endl;
    }

    return 0;
}


Without a new letter on every line:

code:
#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main()
{
    cout << "Please enter a word: ";
    string word;
    cin >> word;
    for( int i = 0; i < word.length(); i++ )
    {
        cout << word[i] << "\a";
    }

    return 0;
}

using std::* is so utterly pointless. Either use "using namespace std;" or just preface everything with "std::". I prefer the latter, though it seems the former is somehow becoming standard practice.

Author:  michaelp [ Wed May 07, 2008 5:03 pm ]
Post subject:  RE:Exercise: Beeping!

I do this sometimes so I know what is in the std namespace. Because sometimes, when books use using namespace std; I'm not really sure if a new concept introduced is in the namespace, so I do that just to remind myself. I will probably stop using std::* and use using namespace std; eventually.

Author:  rdrake [ Wed May 07, 2008 7:42 pm ]
Post subject:  Re: Exercise: Beeping!

A little C#:
C#:
public class Test
{
    public static void Main(string[] args)
    {
        var line = System.Console.ReadLine();

        foreach (var c in line)
        {
            System.Console.Write(c + "\a");
            System.Threading.Thread.Sleep(1000);
        }
    }
}

Author:  HeavenAgain [ Wed May 07, 2008 8:08 pm ]
Post subject:  Re: Exercise: Beeping!

more c..!
c:
#include <stdio.h>

int main()
{
    char line[256];
    gets(line);
    char *i = line;
    while(*i != '\0')
    {
            printf("%c\7", *i++);
            sleep(1000);
    }
    return 0;
}
is there a way to get around the line[256]? so that i dont have to limit the number of characters... hmm... Sad

Author:  CodeMonkey2000 [ Wed May 07, 2008 8:24 pm ]
Post subject:  RE:Exercise: Beeping!

/me waits for zylum to do this in bf.....

Author:  rizzix [ Wed May 07, 2008 9:15 pm ]
Post subject:  RE:Exercise: Beeping!

Haskell:
import Control.Concurrent (threadDelay)

main = getLine >>= mapM_ (\c -> putChar c >> putChar '\a' >> threadDelay 1000000)

Author:  rdrake [ Wed May 07, 2008 9:31 pm ]
Post subject:  Re: Exercise: Beeping!

Since there's so much C/C++, I suppose there should be more Python.

Python:
from time import sleep

def printBeepAndSleep(c):
        print c + "\a"
        sleep(1)

map(printBeepAndSleep, raw_input(""))

Author:  rizzix [ Wed May 07, 2008 10:11 pm ]
Post subject:  RE:Exercise: Beeping!

Scala:
object Test extends Application {
    readLine.foreach { c => print(c + "\07"); Thread sleep 1000}
}

Author:  rizzix [ Wed May 07, 2008 10:18 pm ]
Post subject:  RE:Exercise: Beeping!

Java:
public class Test {
        public static void main(String[] args) {
                for (String c : System.console().readLine().split("")) {
                        System.console().printf(c + "\07");
                        Thread.sleep(1000);
                }
        }
}

Author:  rizzix [ Wed May 07, 2008 10:20 pm ]
Post subject:  RE:Exercise: Beeping!

Hmm why is it that the syntax tags are messing up the "case" of the class names. :s

Author:  btiffin [ Thu May 08, 2008 12:30 am ]
Post subject:  Re: Exercise: Beeping!

Heres one in SNOBOL4
code:
***************************************************************
* Program to output a line, char by char with beeps and delays
*
* Associate TUBE with terminal mode OUTPUT; no newline
        OUTPUT('TUBE', 6, 'T')
* Define specs for CHBEEP and WAIT
        DEFINE('CHBEEP(STRING,DELAY)')
        DEFINE('WAIT(DELAY)')
* BEEP is Control-G
        &ALPHABET LEN(7) LEN(1) . BEEP
* Fetch a line from stdin, end on eof, or beep it out
        LINE = INPUT                            :F(END)
        CHBEEP(LINE,1)                          :(END)
* CHBEEP function peels off characters, displays, beeps, waits
CHBEEP  LINE LEN(1) . CH =                      :F(RETURN)
        TUBE = CH BEEP
        WAIT(DELAY)                             :(CHBEEP)
* WAIT function pauses for DELAY seconds
WAIT    T = TIME()
WAITING LT(TIME() - T, DELAY * 1000)            :S(WAITING)F(RETURN)
* The end
END

Author:  btiffin [ Thu May 08, 2008 3:38 am ]
Post subject:  Re: Exercise: Beeping!

HeavenAgain @ Wed May 07, 2008 8:08 pm wrote:
more c..!
c:
#include <stdio.h>

int main()
{
    char line[256];
    gets(line);
    char *i = line;
    while(*i != '\0')
    {
            printf("%c\7", *i++);
            sleep(1000);
    }
    return 0;
}
is there a way to get around the line[256]? so that i dont have to limit the number of characters... hmm... Sad
Well, yes there is; look into fgets and realloc (or fread or ...) or loop across getch, and then google "buffer overflow" as to why it is not just a limit the number of characters problem. Code like this is susceptible to attack. Learn early and learn often. Potential buffer overflow in C is bad. Very very bad. Learn to avoid it. Write a safe gets for yourself and then carry it with you through your programming career. Bosses will love you and you will help to make the world a better place for everyone. And anyone reading this and thinking, but stdin only accepts 128 or 256 keystrokes; ponder what happens if someone redirects input from a file with 1000 characters and no newline. Then ponder what might happen if those 1000 characters are hand crafted to look like machine instructions.

Sorry for the interruption, but this is an important thing to learn. And when you do, bosses (and co-workers) really will love you for it. Smile

Cheers

Author:  wtd [ Thu May 08, 2008 8:36 am ]
Post subject:  Re: Exercise: Beeping!

rdrake @ Thu May 08, 2008 8:42 am wrote:
A little C#:
C#:
public class Test
{
    public static void Main(string[] args)
    {
        var line = System.Console.ReadLine();

        foreach (var c in line)
        {
            System.Console.Write(c + "\a");
            System.Threading.Thread.Sleep(1000);
        }
    }
}


C#:
public class Test
{
   public static void Main(string[] args)
   {
      System.Console.readLine().ToList().ForEach( ch => { System.Console.Print(ch.ToString() + "\a"; Thread.Sleep(1000) } );
   }
}

Author:  btiffin [ Thu May 08, 2008 12:48 pm ]
Post subject:  Re: Exercise: Beeping!

One in D 1.0 (by a D noob)
D:
// read a line, output each char with a beep and a wait
import std.stdio;
import std.c.time;

void main() {
    char[] buf = readln();
    foreach (char ch ; buf) {
        putc(ch, stderr); putc(7, stderr); msleep(1000);
    }
}

Dang wtd; this is a fun exercise. Great way to waste away coffee breaks.
Edit: trying the syntax tag

Author:  apomb [ Fri May 09, 2008 12:14 am ]
Post subject:  Re: Exercise: Beeping!

Perl:
#! /usr/bin/perl
#prints each letter of a word along with a beep and a one-second delay
#using "length" to find the length of the string

if ($ARGV !=0) {
    print "usage: beeptest word\n";
    exit;
}

$word = $ARGV[0];
$len = length $word;
$| = 1;

#load the array with each letter of "word"
for ($char=0; $char < $len; $char+=1){
    print (substr($word, $char, 1), "\a");
        sleep(1);
}

Author:  wtd [ Fri May 09, 2008 12:28 am ]
Post subject:  RE:Exercise: Beeping!

Pascal!

code:
program BeepTest;
uses crt;
    procedure Beep;
    begin
        write(stdout, #7)
    end;
var
    UserInput : String;
    LenOfUserInput, I : Integer;
begin
    ReadLn(UserInput);
    LenOfUserInput := Length(UserInput);

    for I := 1 to LenOfUserInput do
    begin
        write(UserInput[I]);
        delay(1000);
        beep
    end
end.

Author:  apomb [ Fri May 09, 2008 12:40 am ]
Post subject:  RE:Exercise: Beeping!

variation to my previous one:

Perl:

#! /usr/bin/perl
#prints each letter of a word along with a beep and a one-second delay
#using "length" to find the length of a string
$| = 1;

if ($ARGV != 0) {
    print "usage: beeptest word";
    exit;
}

$word = $ARGV[0];
$len = length $word;

#load the array with each letter of "word"
for ($char = 0; $char < $len; $char += 1){
    @letters [$char] = substr ($word, $char, 1);
        sleep (1);
}

foreach $letter (@letters){
    print "$letter\a"; sleep(1);
}


as you can see in the first one, i forgot to take the comment out when i took out the array and foreach loop. this is what my original idea looked like, and it stil works, its just a little longer

Author:  wtd [ Fri May 09, 2008 12:46 am ]
Post subject:  RE:Exercise: Beeping!

code:
$| = 1; map { print "$_\a"; sleep(1) } split //, #ARGV[0]

Author:  btiffin [ Fri May 09, 2008 9:07 pm ]
Post subject:  Re: Exercise: Beeping!

The palindrome exercise made me think about Icon, so heres a beeper in Icon
Icon:
###############################################################
# Program to read a line; display each char with beep and delay
procedure main()
    every writes(!read(), char(7), delay(1000))
end

Author:  btiffin [ Sat May 10, 2008 7:51 pm ]
Post subject:  Re: Exercise: Beeping!

Here's one if Forth, gforth in particular
gforth:
: chbeep  pad dup 80 accept  + pad  do i c@ emit 7 emit 1000 ms loop ;  chbeep

Author:  michaelp [ Sun May 11, 2008 7:56 am ]
Post subject:  RE:Exercise: Beeping!

Some of this code looks so confusing to me! Although Pascal looks very straightforward. Very Happy

Author:  btiffin [ Sun May 11, 2008 11:31 am ]
Post subject:  Re: RE:Exercise: Beeping!

michaelp @ Sun May 11, 2008 7:56 am wrote:
Some of this code looks so confusing to me! Although Pascal looks very straightforward. Very Happy

Never fear michealp. Smile The compsci arena is so vast, that you have to carefully pick and choose the areas of expertise. No one knows it all. Don't even try, imho. But, I would suggest exploring as much as you can. All the different angles will make you better in the areas you do build up expertise in. Programming languages are much like human languages. No one knows them all.

My choice of well-rounded knowledge; Assembler, AWK, bash, BASIC, Logo, Smalltalk, Pascal, Lisp, COBOL, Fortran, Prolog, C, C++, D, Java, Eiffel, Erlang, Python, perl, Ruby, Oz, J, R, SNOBOL, Icon, Forth, REBOL. Those environments cover a lot (but not all) of the bases and paradigms. Given those, picking up the syntax of any other language becomes a lot easier. And those are my personal opinions. Your mileage will vary. For instance; learning Java is far more than just the syntax. There are common mistakes, idioms, thousands of ready made classes and entire libraries to learn on the way to mastery. This applies to most programming environments.

This weekend I'm playing in Inform 7 (pretty much programming in English ... and I dozed off too much in English class; relearning basic sentence structure and concise grammar; but it is kinda fun). Luckily, just about every language now has open and free implementations so exploring won't cost you anything but time.

Note; my list is fairly long, but I've been doing this for 30 years now. Don't think you need to have all this under your belt the first week. My short list is Assembler, bash, AWK, C, Icon, Forth, REBOL (again a very personal list choice - and I don't do Windows - again personal choice, but it means I can't/don't apply for the plethora of .NET jobs out there).

If you ever get bored, check out http://en.wikipedia.org/wiki/Categorical_list_of_programming_languages and try and pick one or two languages from each of the categories (over time - there are 40 of them, last I looked). You don't have to explore the breadth and depth of each, but getting past Hello World and then a small exercise or two should do to make you a world class coder able to take on anything and everything in whatever environment management may throw at you.

Cheers

Author:  michaelp [ Sun May 11, 2008 11:47 am ]
Post subject:  RE:Exercise: Beeping!

I know C++. But all of the other stuff is very confusing to me.
Thanks for that though + that link. Very Happy

Author:  btiffin [ Wed Jun 11, 2008 10:10 pm ]
Post subject:  Re: Exercise: Beeping!

I can't leave this one alone. It has become my language refresher exercise. Smile
This would have looked shorter, but DISPLAY char WITH BELL NO ADVANCING END-DISPLAY was no good
OpenCOBOL 1.1 http://www.opencobol.org/
COBOL:
      * Beeper.cob for compsci.ca exercise
      ** Read a line of user input, display each character with a
      ** 1 second delay and a beep.
       IDENTIFICATION DIVISION.
       PROGRAM-ID. beeper IS INITIAL.
       AUTHOR. Brian Tiffin.
       SECURITY. None.
       INSTALLATION. http://www.compsci.ca.
       DATE-WRITTEN. 11-June-2008.
       DATE-COMPILED.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 USER-DATA                    PIC X(80) VALUE SPACES.
       01 CHAR-COUNT                   PIC 99 VALUE ZEROES.
       01 CHAR-INDEX                   PIC 99 VALUE ZEROES.

       PROCEDURE DIVISION.
       BEGIN.
      * Fancy up the screen; work around for display
       DISPLAY SPACE WITH
           FOREGROUND-COLOR 3
           BACKGROUND-COLOR 1
           BLANK SCREEN
       END-DISPLAY
      * get the input   
       DISPLAY ": " WITH NO ADVANCING.
       ACCEPT USER-DATA.
      * get the user input length by scanning back for non space
       PERFORM VARYING CHAR-COUNT FROM 80 BY -1
           UNTIL USER-DATA(CHAR-COUNT:1) NOT = SPACE
       END-PERFORM
      * output each character with a beep and then pause
       PERFORM VARYING CHAR-INDEX FROM 1 BY 1
           UNTIL CHAR-INDEX > CHAR-COUNT
           DISPLAY USER-DATA(CHAR-INDEX:1)
               LINE 3 COLUMN CHAR-INDEX WITH BELL
           END-DISPLAY
           CALL "C$SLEEP" USING "1"
       END-PERFORM.
       EXIT PROGRAM.


I hope no one minds if I reopened a month-old.

And yes COBOL is indented 8 spaces, column 7 is * for comment, and the first 6 spots are reserved for punch card deck numbers. When a coder dropped a box of cards (one line per card, 80 spaces) on the floor before getting them loaded into a reader ... think of playing 52 card pick up with 2000 cards and you have to pick them up in order ... so they "numbered" the lines of source code in the source code, just in case. Smile

And a stupid trivia (myth?) item; the size of a punch card had something to do with the size of the American dollar bill for easy access to cutting machines and boxes.

Nowadays COBOL can be freeform, removing the 1-6, 7, 8-72 special columns, making edits easier. OpenCOBOL defaults to FIXED form, unless you
code:
$ cobc -free -x beeper.cob


And don't fear the COBOL. Boomers are at 60, the COBOL crunchers get paid top dollar, there are billions of lines of legacy, you may get to play with big-iron on top-secret stuff, and well, it can make for a lucrative gig. OpenCOBOL is free, supports a lot of the COBOL 85 standard, a fair chunk of 2002, other common extensions, links with C; so learning COBOL only costs time.

Reserved word heavy the COBOL is. My OC 1.1 build has 510 show up with cobc --list-reserved | wc. To me thats titillating; wanting to know what all the words can help me with or teach me, before I even crack open any libraries.

Cheers

Author:  r691175002 [ Wed Jun 11, 2008 10:48 pm ]
Post subject:  Re: Exercise: Beeping!

Actionscript 3.0:
code:
import flash.events.*;

var tField:TextField = new TextField();
tField.width = 550;
tField.height = 400;
tField.type = TextFieldType.INPUT;

var sInput:String;
var nIndex:Number = 0;
var nFrame:Number = 0;

function keyListener(e:KeyboardEvent):void {
        if (e.keyCode == Keyboard.ENTER) {
                tField.type = TextFieldType.DYNAMIC;
                sInput = tField.text;
                tField.appendText("\n");
        }
}
function frameListener(e:Event):void {
        if (sInput != null) {
                nFrame++;
                if (nFrame >= 30) {
                        tField.appendText(sInput.substr(nIndex,1));
                        nIndex++;
                        if (nIndex > sInput.length)
                                sInput = null;
                        nFrame = 0;
                }
        }
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyListener);
stage.addEventListener(Event.ENTER_FRAME, frameListener);
stage.addChild(tField);
stage.frameRate = 30;

A pretty roundabout way of doing it, flash is way too high level for this kind of stuff. Also, you cannot generate sounds or output the bell character using only code.

Author:  alex.john95 [ Thu Jul 31, 2008 11:52 am ]
Post subject:  RE:Exercise: Beeping!

Very Funny...


: