406
votes

I'm looking for the coolest thing you can do in a few lines of simple code. I'm sure you can write a Mandelbrot set in Haskell in 15 lines but it's difficult to follow.

My goal is to inspire students that programming is cool.

We know that programming is cool because you can create anything you imagine - it's the ultimate creative outlet. I want to inspire these beginners and get them over as many early-learning humps as I can.

Now, my reasons are selfish. I'm teaching an Intro to Computing course to a group of 60 half-engineering, half business majors; all freshmen. They are the students who came from underprivileged High schools. From my past experience, the group is generally split as follows: a few rock-stars, some who try very hard and kind of get it, the few who try very hard and barely get it, and the few who don't care. I want to reach as many of these groups as effectively as I can. Here's an example of how I'd use a computer program to teach:

Here's an example of what I'm looking for: a 1-line VBS script to get your computer to talk to you:

CreateObject("sapi.spvoice").Speak InputBox("Enter your text","Talk it")

I could use this to demonstrate order of operations. I'd show the code, let them play with it, then explain that There's a lot going on in that line, but the computer can make sense of it, because it knows the rules. Then I'd show them something like this:

4(5*5) / 10 + 9(.25 + .75)

And you can see that first I need to do is (5*5). Then I can multiply for 4. And now I've created the Object. Dividing by 10 is the same as calling Speak - I can't Speak before I have an object, and I can't divide before I have 100. Then on the other side I first create an InputBox with some instructions for how to display it. When I hit enter on the input box it evaluates or "returns" whatever I entered. (Hint: 'oooooo' makes a funny sound) So when I say Speak, the right side is what to Speak. And I get that from the InputBox.

So when you do several things on a line, like:

x = 14 + y;

You need to be aware of the order of things. First we add 14 and y. Then we put the result (what it evaluates to, or returns) into x.

That's my goal, to have a bunch of these cool examples to demonstrate and teach the class while they have fun. I tried this example on my roommate and while I may not use this as the first lesson, she liked it and learned something.

Some cool mathematica programs that make beautiful graphs or shapes that are easy to understand would be good ideas and I'm going to look into those. Here are some complicated actionscript examples but that's a bit too advanced and I can't teach flash. What other ideas do you have?

6
  • 6
    "my goal is to inspire students that programming is cool." I don't think you can tell people programming is cool. Either they like it, or they don't.
    – Rik
    May 1, 2009 at 12:18
  • 2
    Your one line VBS script doesn't work on my Mac! :-P Good question though. May 1, 2009 at 12:23
  • 1
    I allways like this kind of stuff, but who you are trying to impress, me the Sierpinski gasket one would do I nice job. For an IT guys may something that creates files, for some people making the computer talk would be impressive, and so on. So what matter is the target audience, then you define whats cool.
    – Oakcool
    May 1, 2009 at 17:05
  • 1
    @Oakcool: The gasket is impressive, and students are easy to impress. But I taught intro to some 400 students at BC, and I'm doing a little now. The trick is to get THEM to do it, in baby steps, from ground zero up to being able to do something useful. The big lesson I learned is GO... SLOW... May 1, 2009 at 18:45
  • I think it would be cool if every answerets put an image of the result in their post. I think it would be easier for OP (Tom Ritter) to show it off then to its students. Well , that's my opinion.. :-) May 18, 2009 at 22:17

87 Answers 87

1 2
3
0
votes

First To get maximum attention at minimum time, you'll want to use a high-level language. probably you'll want to show 3D.

I'd go with Opengl - I'd start by showing a short scene from a 3d computer game, then explaining, that this was done by dividing the big program into smaller parts, and then showing them how a little part may look like. something like lesson 05 on nehe.gamedev.net, or maybe even a more advanced lesson. it's quite impressive, and not too complicated.

Also you may want to check Alice which contains 3d and was designed to teach..

2
  • OpenGL has so many boring low level details. It always bore me when I Was trying to learn it. Specially when the tutorial is based in Win32 API, which is even more boring!!!!
    – hasen
    May 4, 2009 at 1:02
  • There is a difference between learning something to the tiniest details, and giving a short demo followed by a brief overview of the big idea. May 4, 2009 at 7:00
0
votes

When I was a little kid, I had a keen interest in computers (MSX back then), and consequently programming (all there was, was a variant of Basic). I lost that after I grew up, but I got back to it when I learned that Counter-Strike was just a mod made by some fans by modifying Half-Life code. That made me really interested in programming all over again!

It's not 10 lines of code, but if you show people the source code for some game, and then modify that and make it do something different, and demonstrate it to them live, it's reaaaaally gonna blow them away. Wow, this actually is not dark magic! You can do it!

Now a days, there are quite a few games you can do this with. I think the source code for all the Quake series (atleast I through III) is released. I know for a fact that you can create mods for Half-Life and Half-Life2, I'm sure other games like Unreal and FarCry also offer a similar ability.

Some simple things that could spark grate motivation:

  • Make a weapon super powerful (e.g., infinite ammo, higher damage, auto-aim .. etc.
  • Add an Anime-style movement (flying, dashing really fast, etc).

The modification itself shouldn't take too many lines of code, but the fact that it works is just amazing.

0
votes

I wrote this for a forum game -- writing the ROT13 algorithm in as few lines as possible. So, how about this in C?

rot13(char*s)
{
    int i=-1;
    do{
        i++;
        s[i] = (s[i] >= 65 && s[i] <=90 || s[i] >= 97 &&s [i] <= 122) ?
            ((s[i] < 97) ? 65 : 97) + (((s[i] - ((s[i] < 97) ? 65 : 97)) + 13) % 26) :
            s[i];
    } while(s[i] > 0);
}

I think the ternary operator is pretty neat, though I hear it is slower than if constructs. I have yet to time it for myself...

3
  • The ternary operator is useful if not overused, but I don't see how this code will do anything but confuse students.
    – danio
    May 5, 2009 at 9:10
  • 4
    For the love of god don't show this to your students.
    – OEP
    May 5, 2009 at 13:08
  • Did you mean 'many' instead of 'few'? hea-www.harvard.edu/~fine/Tech/rot13.html
    – sigfpe
    Dec 30, 2011 at 23:30
0
votes

Inspired by Robin Day and John Topley's answers, get them to paste the following into the address bar oftheir browser:

javascript:var name=prompt("What is your name?", "");var msg='Hello '+name+'<br>';newwindow=window.open();newdocument=newwindow.document;for (var i=0;i<100;i++){newdocument.write(msg);}newdocument.close();

Or more readably:

var name=prompt("What is your name?", "");
var msg='Hello '+name+'<br>';
newwindow=window.open();
newdocument=newwindow.document;
for (var i=0;i<100;i++)
{
    newdocument.write(msg);
}
newdocument.close();
0
votes

The Mandelbrot Set can be presented in a way that isn't terribly complex, for example in Java below:

public class MiniMandelbrot {
    public static void main(String[] args) {
        int[] rgbArray = new int[256 * 256];
        for (int y=0; y<256; y++) {
            for (int x=0; x<256; x++) {
                double cReal=x/64.0-2.0, cImaginary=y/64.0-2.0;
                double zReal=0.0, zImaginary=0.0, zRealSquared=0.0, zImaginarySquared=0.0;
                int i;
                for (i = 0; (i < 63) && (zRealSquared + zImaginarySquared < 4.0); i++) {
                    zImaginary = (zReal * zImaginary) + (zReal * zImaginary) + cImaginary;
                    zReal = zRealSquared - zImaginarySquared - cReal;
                    zImaginarySquared = zImaginary * zImaginary;
                    zRealSquared = zReal * zReal;
                }
                rgbArray[x+y*256] = i * 0x040404;
            }
        }
        java.awt.image.BufferedImage bufferedImage = new java.awt.image.BufferedImage(256, 256, 1);
        bufferedImage.setRGB(0, 0, 256, 256, rgbArray, 0, 256);
        javax.swing.JOptionPane.showMessageDialog(null, new javax.swing.ImageIcon(bufferedImage), "The Mandelbrot Set", -1);
    }
}
0
votes

This is by far the coolest thing I've seen... and when broken down, it's actually pretty simple:

http://blogs.msdn.com/lukeh/archive/2007/04/03/a-ray-tracer-in-c-3-0.aspx

0
votes

A bit off topic but you can check out this tweet coding which used as3 code that was less than 140 characters:

http://gskinner.com/playpen/tweetcoding_0/

^_^

0
votes

Recursion can also be used to solve a maze. Just like the Sierpinski triangle and other art, for me this is much more fun than solving some mathematical problem.

0
votes

10 Print "Mohan"
20 Goto 10

0
votes

I've always liked the Tower of Hanoi. In Scheme

(define (hanoi x from to spare)
  (if (= x 1)
    (begin
      (display "move ")(display from)(display " to ")(display to)(display "\n"))
  (begin
    (hanoi (- x 1) from spare to)
    (hanoi 1 from to spare)
    (hanoi (- x 1) spare to from))))

Example output

gosh> (hanoi 3 'start 'dest 'spare)
move start to dest
move start to spare
move dest to spare
move start to dest
move spare to start
move spare to dest
move start to dest
#<undef>

Also in Python (though this can't do 1000 discs like the Scheme version can)

def hanoi(x, source, dest, spare):
  if x == 1:
    print "%s to %s" % (source, dest)
  else:
    hanoi(x - 1, source, spare, dest)
    hanoi(1, source, dest, spare)
    hanoi(x - 1, spare, dest, source)
0
votes

Building on top of the SAPI example you provided, I use this to read files out loud to myself (just drag and drop a text file onto it's icon or run it from the command line)

speakfile.vbs:

strFileName = Wscript.Arguments(0)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, 1)
strText = objFile.ReadAll
Set objVoice = CreateObject("SAPI.SpVoice")
objVoice.Speak strText
0
votes

A basic grep application in Ruby/Python/Perl.

0
votes

How about Processing for JavaScript? I don't know Processing, but the code always seems rather small for what it can do, it's very visual, and you can run it in a browser.
http://processingjs.org/exhibition

0
votes

Something like ...

10 rem twelve times table

20 For x = 1 to 12

30  For y = 1 to 12

40     print using"####";x*y;

50  next y

60  print 

70 next x

80 end
0
votes

Convert an image to music in Python

From my answer to How do I loop through every 4th pixel in every 4th row, using Python?:

#!/usr/bin/env python
import easygui # http://easygui.sourceforge.net/
import Image   # http://www.pythonware.com/products/pil/
import numpy   # http://numpy.scipy.org/

filename = easygui.fileopenbox() # pick a file
im = Image.open(filename) # make picture
im.show() # show picture
ar = numpy.asarray(im) # get all pixels
N = 4
pixels = ar[::N,::4]  # every 4th pixel in every N-th row
notes = pixels.sum(axis=2) / 9 + 24 # compute notes [0, 52]
print "number of notes to play:", notes.size

Notes can correspond to different tones. I use here equal tempered scale:

# play the notes
import audiere # http://pyaudiere.org/
import time

d = audiere.open_device()
# Notes in equal tempered scale 
f0, a = 440, 2**(1/12.)
tones = [d.create_tone(f0*a**n) for n in range(-26, 27)] # 53

for y, row in enumerate(notes):
    print N*y # print original row number
    for t in (tones[note] for note in row):
        t.volume = 1.0 # maximum volume
        t.play()
        time.sleep(0.1) # wait around 100 milliseconds
        t.stop()
0
votes

You can use jQuery(Write Less,Do More) library to achieve splendid visual effect in HTML webforms with minimal coding. Otherwise functional languages like F# too can do lots of stuff with few lines of codes . Following is solution for problem number 8 of Project euler :-

data :- string of numbers in 50 * 20 grid

let data = txt |> Seq.toList |> List.filter System.Char.IsDigit |> List.map System.Char.GetNumericValue

let rec partition_5 l = match l with | x1::(x2::x3::x4::x5::_ as t) -> [x1;x2;x3;x4;x5]::(partition_5 t) | _ -> []

let euler_8 = List.map (fun x -> List.fold (*) 1.0 x) (partition_5 data) |> List.max

0
votes

hmm, I remember making snowflakes and fire in QBasic when a friend came by and showed me how to do a rotating 3D cube and totally blew my mind.

And then I modified my fire onto the cube and it was good times.

Have to see if I can find those old scripts somewhere, they weren't very lengthy.

0
votes

I think some cool expiriments in Python with NodeBox would be a cool start. It has functions to draw things from squares to complex paths. It can even take in images from the Mac iSight/ Webcam and manipulate it by scaling, rotating and applying filters.

Sadly, it's only for Mac OS X, so I don't think it would be of much use to teach it, but as an example (if you have a Mac yourself) for what's possible with a little bit of code, it would be pretty nifty.

0
votes

My first program is somewhat similar to one already mentioned here, but my is one line shorter and much more polite:

10 PRINT "What is your name?"
20 INPUT A$
30 PRINT "Thanks"
0
votes

At http://www.youtube.com/watch?v=a9xAKttWgP4 you can watch Conway's Game Of Life programmed (and simultaneously verbally commented) in about 5 lines of APL (A Programming Language).

It's fun to watch and can inspire students that programming is cool, and math, and mathematical, concise programming languages :)

BTW, Uncle Bob Martin mentioned this youtube video on a hanselminutes podcast.

1
  • I'm not absolutely sure APL is the first language you want to introduce beginners to. :)
    – ShdNx
    Nov 23, 2011 at 12:18
0
votes

Squeak is a good tool for inspire

E.g: http://squeakland.jp/school/drive_a_car/html/Drivecar12.html

0
votes

Here's my 10 line web spider. Technically it's 11 including the perl shell declaration but I hope that's forgivable!

I wanted to get it to identify certain file types and support relative paths, but ran out of lines!

To run:

perl spider.pl http://yahoo.com/search?q=test

Note that Google doesn't allow LWP Simple without a user agent so searching Google won't work. No room for that either! Anyway, where's the code:

#!/usr/bin/perl -w
use LWP::Simple;
my @queue = ($ARGV[0]);
my %visited = ();
while (my $url = pop(@queue)) {
    next if $visited{$url};
    $visited{$url} = 1;
    my $html = get($url) or next;
    print "Spidering $url\n";
    push(@queue, $html =~ m/(http:\/\/[^'"]*)/g);
}
0
votes

Use games! Not coding games, but coding competitions. Think of the Google AI challenge, and dumb it down.

Let me give an example. I once made a little contest with my friends: one of us set up a framework for a simulation, and the rest coded an AI ranging from the simple to the heavily analitic, and we fired a hundred runs to see which AI performed best.

The framework? Basic I/O: the simulation control was executed by a process that spawned one child per competing AI, and each round of the simulation wrote data to the standard input pipes, and read the outputs. This way, we could write our AIs in whatever language we wanted, just by following a very simple protocol.

The rules were terribly simple, yet the thing was challenging: we had two villages, A and B, which distributed money equally among the families that lived there. A had 800 coins to give, and B had 500. Each round, all of the AIs were asked to chose a village to live in (printing 'A' or 'B' to stdout), and then got back the totals for each village during that period (by reading numbers from stdin). The goal was to have the most money after a hundred rounds.

Some of the AIs we created had really complex mechanisms to try and guess what village to settle in -- though they weren't really good, for the winner was a strategy that simply always picked the village that gave the least money to each family last round (assuming most would move out to the other village the next time).

I think this is engaging, encourages research and is a healthy way of competition. There are thousands of games that could be played, and it only requires basic programming knowledge (standard I/O!) for the players to interact.

0
votes

Here is something fun using javascript

function checkLove(love)
{
    if (love)
        alert("He he he, cool!");
    else
    {
        if(love != undefined) alert("Sorry, you must love me.");
        checkLove(confirm("Do you love me?"));
    }
}
checkLove();

It's kindof only 10 lines! You can either include it it a webpage or just copy paste the below code in your browser's url bar and hit enter

javascript:function checkLove(love){if (love)alert("He he he, cool!");else{if(love != undefined) alert("Sorry, you must love me.");checkLove(confirm("Do you love me?"));}}checkLove();

Fun, right?

-1
votes

Messing around with cookies.

Its cookies! Kids loooovvve cookies!

  1. Find a site that relies on cookies for something.
  2. Use firefox addon to edit the cookie.
  3. ????
  4. Learning!!!
-1
votes

From Quake 3 I believe, a very fast 1/sqrt(x):

#include <stdio.h>
#include <stdlib.h>
int main (int argc, char const* argv[])
{
    if (argc != 2) {
        printf("Need a number!\n");
        return 0;
    }
    float number = atof(argv[1]);
    long i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;  // evil floating point bit level hacking
    i  = 0x5f3759df - ( i >> 1 ); // what the?
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
    printf("%f\n", y);
    return 0;
}
1
1 2
3

Not the answer you're looking for? Browse other questions tagged or ask your own question.