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 [1] 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 [2], 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 [3] that are easy to understand would be good ideas and I'm going to look into those. Here are some complicated actionscript examples [4] but that's a bit too advanced and I can't teach flash. What other ideas do you have?
Enter this code in your address bar (in your browser) and press enter. Then you can edit all the content of the webpage!
javascript:document.body.contentEditable='true'; document.designMode='on'; void 0
That is the coolest "one-liner" I know =)
javascript:
and void 0
are boilerplate: the equivalent of int main() {
and return 0; }
in C. And the other two lines are just different browser APIs that do the same thing: The first is the IE API, the second is the NetScape API. HTML5 uses contentEditable
, so unless you care about supporting Firefox 1.5 or something, the actual code amounts to: document.body.contentEditable='true';
- Zarel
When I first wrote this.
10 PRINT "What is your name?"
20 INPUT A$
30 PRINT "Hello " A$
40 GOTO 30
It blew people away! The computer remembered their name!
EDIT: Just to add to this. If you can convince a new programmer this is the coolest thing they can do, they will become the good programmers. These days, you can do almost anything you want with one line of code to run a library somebody else wrote. I personally get absolutely no satisfaction from doing that and see little benefit in teaching it.
OK, it's 15 lines of code but the result is awesome! That's the kind of stuff that made me freak out when I was a child. This is from the PHP manual:
$x = 200;
$y = 200;
$gd = imagecreatetruecolor($x, $y);
$corners[0] = array('x' => 100, 'y' => 10);
$corners[1] = array('x' => 0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);
$red = imagecolorallocate($gd, 255, 0, 0);
for ($i = 0; $i < 100000; $i++) {
imagesetpixel($gd, round($x),round($y), $red);
$a = rand(0, 2);
$x = ($x + $corners[$a]['x']) / 2;
$y = ($y + $corners[$a]['y']) / 2;
}
header('Content-Type: image/png');
imagepng($gd);
Microsoft has Small Basic [1], an IDE for "kids".
pic = Flickr.GetRandomPicture("beach")
Desktop.SetWallpaper(pic)
It is specifically designed to show how cool programming is.
[1] http://msdn.microsoft.com/en-us/beginner/ff384126.aspxI tend to think that people are impressed with stuff that they can relate to or is relevant to their lives. I'd try and base my 10 lines of code around something that they know and understand. Take, for example, Twitter and its API. Why not use this API to build something that's cool. The following 10 lines of code will return the "public timeline" from Twitter and display it in a console application...
using (var xmlr = XmlReader.Create("http://twitter.com/statuses/public_timeline.rss"))
{
SyndicationFeed
.Load(xmlr)
.GetRss20Formatter()
.Feed
.Items
.ToList()
.ForEach( x => Console.WriteLine(x.Title.Text));
}
My code sample might not be the best for your students. It's written in C# and uses .NET 3.5. So if you're going to teach them PHP, Java, or C++ this won't be useful. However, my point is that by associating your 10 lines of code with something "cool, interesting, and relevant to the students your sample also becomes cool, interesting, and relevant.
Good luck!
[Yes, I know that I've missed out a few lines of using statements and the Main method, but I'm guessing that the 10 lines didn't need to be literally 10 lines]
This is a Python telnet server that will ask for the users name and say hello to them. This looks cool because you are communicating with your program from a different computer over the network.
from socket import *
s=socket(AF_INET, SOCK_STREAM)
s.bind(("", 3333))
s.listen(5)
while 1:
(c, a) = s.accept()
c.send("What is your name? ")
name = c.recv(100)
c.send("Hello "+name)
c.close()
I got a great response from my kids with a quick VB script to manipulate a Microsoft Agent character. For those that aren't familiar with MS Agent, it's a series of animated onscreen characters that can be manipulated via a COM interface. You can download the code and characters at the Microsoft Agent [1] download page.
The folllowing few lines will make the Merlin character appear on screen, fly around, knock on the screen to get your attention, and say hello.
agentName = "Merlin"
agentPath = "c:\windows\msagent\chars\" & agentName & ".acs"
Set agent = CreateObject("Agent.Control.2")
agent.Connected = TRUE
agent.Characters.Load agentName, agentPath
Set character = agent.Characters.Character(agentName)
character.Show
character.MoveTo 500, 400
character.Play "GetAttention"
character.Speak "Hello, how are you?"
Wscript.Sleep 15000
character.Stop
character.Play "Hide"
There are a great many other commands you can use. Check http://www.microsoft.com/technet/scriptcenter/funzone/agent.mspx for more information.
EDIT 2011-09-02 I recently discovered that Microsoft Agent is not natively installed on Windows 7. However it is offered as a separate download here [2]. I have not tested this so cannot verify whether it operates.
[1] http://www.microsoft.com/downloads/details.aspx?familyid=E11BF712-7862-45BA-826D-44AE3A11836F&displaylang=enI think it's tough to be a computer educator these days. I am. We face an increasingly steep uphill battle. Our students are incredibly sophisticated users and it takes a lot to impress them. They have so many tools accessible to them that do amazing things.
A simple calculator in 10 lines of code? Why? I've got a TI-86 for that.
A script that applies special effects to an image? That's what Photoshop is for. And Photoshop blows away anything you can do in 10 lines.
How about ripping a CD and converting the file to MP3? Uhh, I already have 50,000 songs I got from BitTorrent. They're already in MP3 format. I play them on my iPhone. Who buys CDs anyway?
To introduce savvy users to programming, you're going to have to find something that's:
a) applicable to something they find interesting and cool, and b) does something they can't already do.
Assume your students already have access to the most expensive software. Many of them do have the full version of Adobe CS5.5 (retail price: $2,600; actual price: free) and can easily get any application that would normally break your department's budget.
But the vast majority of them have no idea how any of this "computer stuff" actually works.
They are an incredibly creative bunch: they like to create things. They just want to be able to do or make something that their friends can't. They want something to brag about.
Here are some things that I've found to resonate with my students:
None of these involve any programming in the traditional sense. But they do leverage powerful libraries. I think of them as a different kind of programming.
[1] http://pipes.yahoo.comI've found a big favorite (in GWBASIC) is:
10 input "What is your name ";N$
20 i = int(rnd * 2)
30 if i = 0 print "Hello ";N$;". You are a <fill in insult number 1>"
40 if i = 1 print "Hello ";N$;". You are a <fill in insult number 2>"
I've found beginning students have a few conceptions that need to be fixed.
Good luck with your class. I'm sure you'll do well.
P.S. I'm sure you understand that, along with material and skill, you're also teaching an attitude, and that is just as important.
This C-code is maybe be obfuscated, but I found it very powerful
#include <unistd.h>
float o=0.075,h=1.5,T,r,O,l,I;int _,L=80,s=3200;main(){for(;s%L||
(h-=o,T= -2),s;4 -(r=O*O)<(l=I*I)|++ _==L&&write(1,(--s%L?_<L?--_
%6:6:7)+"World! \n",1)&&(O=I=l=_=r=0,T+=o /2))O=I*2*O+h,I=l+T-r;}
And here is the result... In only 3 lines...
A kind of fractal Hello World
...
WWWWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWooooooooooooooooorrrrrrrrrrrrrrrrrrrrroooooooooooooooooooooooooooo
WWWWWWWWWWWoooooooooooorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrooooooooooooooooooooo
WWWWWWWWWWooooooooorrrrrrrrrrrrrrrrrrrrrrrllllld!!ddllllrrrrrrooooooooooooooooo
WWWWWWWWoooooooorrrrrrrrrrrrrrrrrrrrrrllllllldd!oWW!!dllllllrrrrroooooooooooooo
WWWWWWWoooooorrrrrrrrrrrrrrrrrrrrrrlllllllldddd!orro!o!dllllllrrrrrrooooooooooo
WWWWWWooooorrrrrrrrrrrrrrrrrrrrrllllllllldddd!WorddddoW!ddllllllrrrrrrooooooooo
WWWWWoooorrrrrrrrrrrrrrrrrrrrrlllllllllddd!!!o!!! !dWW!ddddllllrrrrrrrooooooo
WWWWooorrrrrrrrrrrrrrrrrrrrllllllllldd!!!!WWWoo WloW!!!ddddllrrrrrrrrooooo
WWWWoorrrrrrrrrrrrrrrrrrrlllllllddddWldolrrlo!Wl r!dlooWWWoW!dllrrrrrrroooo
WWWoorrrrrrrrrrrrrrrrrlllllddddddd!!Wdo l! rdo!l!r!dlrrrrrrrrooo
WWoorrrrrrrrrrrrrrrlllddddddddd!!!!oolWW lW!ddlrrrrrrrroo
WWorrrrrrrrrrrrllld!!!!!dddd!!!!WWrd ! rlW!ddllrrrrrrrro
Worrrrrrrllllllddd!oooWWWoloWWWWoodr drrWdlllrrrrrrrr
Worrrlllllllldddd!WolWrr!!dWWWlrrldr ro!dlllrrrrrrrr
Wrrllllllllddddd!WWolWr oWoo r!dllllrrrrrrr
Wlllllllldddd!!odrrdW o lWddllllrrrrrrr
Wlddddd!!!!!WWordlWrd oW!ddllllrrrrrrr
olddddd!!!!!WWordlWrd oW!ddllllrrrrrrr
Wlllllllldddd!!odrrdW o lWddllllrrrrrrr
Wrrllllllllddddd!WWolWr oWoo r!dllllrrrrrrr
Worrrlllllllldddd!WolWrr!!dWWWlrrldr ro!dlllrrrrrrrr
Worrrrrrrllllllddd!oooWWWoloWWWWoodr droWdlllrrrrrrrr
WWorrrrrrrrrrrrllld!!!!!dddd!!!!WWrd ! rlW!ddllrrrrrrrro
WWoorrrrrrrrrrrrrrrlllddddddddd!!!!oolWW lW!ddlrrrrrrrroo
WWWoorrrrrrrrrrrrrrrrrlllllddddddd!!Wdo l! rdo!l!r!dlrrrrrrrrooo
WWWWoorrrrrrrrrrrrrrrrrrrlllllllddddWldolrrlo!Wl r!dlooWWWoW!dllrrrrrrroooo
WWWWooorrrrrrrrrrrrrrrrrrrrllllllllldd!!!!WWWoo WloW!!!ddddllrrrrrrrrooooo
WWWWWoooorrrrrrrrrrrrrrrrrrrrrlllllllllddd!!!o!!! WdWW!ddddllllrrrrrrrooooooo
WWWWWWooooorrrrrrrrrrrrrrrrrrrrrllllllllldddd!WorddddoW!ddllllllrrrrrrooooooooo
WWWWWWWoooooorrrrrrrrrrrrrrrrrrrrrrlllllllldddd!orro!o!dllllllrrrrrrooooooooooo
WWWWWWWWoooooooorrrrrrrrrrrrrrrrrrrrrrllllllldd!oWW!!dllllllrrrrroooooooooooooo
WWWWWWWWWWooooooooorrrrrrrrrrrrrrrrrrrrrrrllllld!!ddllllrrrrrrooooooooooooooooo
WWWWWWWWWWWoooooooooooorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrooooooooooooooooooooo
WWWWWWWWWWWWWooooooooooooooooorrrrrrrrrrrrrrrrrrrrroooooooooooooooooooooooooooo
WWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWWWWWWoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWWWWWWWWoooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
How about showing that you can take any web browser and enter JavaScript into the address bar and get code to execute?
EDIT: Go to a page with lots of images and try this in the address bar:
javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length; function A(){for(i=0; i<DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5; DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5}R++ }setInterval('A()',5); void(0)
You could make an application that picks a random number. And you have to guess it. If you are wrong it says: higher or lower. And if you guessed it, a nice message.
It's cool to play for the students.
Simple Python version without proper error checking:
import random
while input('Want to play higher/lower? ').lower().startswith('y'):
n = random.randint(1, 100)
g = int(input('Guess: '))
while g != n:
print(' %ser!' % (g > n and 'low' or 'high'))
g = int(input('Guess: '))
print(' Correct! Congratulations!')
Erik [1] suggests that the computer should guess the number. This can be done within 10 lines of code as well (though now the lack of proper error checking is even more serious: valid numbers outside the range cause an infinite loop):
while input('Want to let the pc play higher/lower? ').lower().startswith('y'):
n = int(input('Give a number between 1 and 100: '))
lo, hi, guess, tries = 1, 100, 50, 1
while guess != n:
tries += 1
lo, hi = (guess + 1, hi) if guess < n else (lo, guess - 1)
guess = (lo + hi) // 2
print('Computer guessed number in %d tries' % tries)
[1] https://stackoverflow.com/users/16942/erikeval(raw_input(prompt))
. See input. - Jeff Kaufman
Back in computer class in high school, myself and a couple of friends taught the class how to program with Delphi. The class was mostly focused on programming with Pascal, so Delphi was a good next step. We demonstrated the event driven nature of Delphi and its RAD capabilities. At the end of the lesson we showed the class a sample application and asked them to reproduce it. The application asked "Are you drunk?" with two buttons Yes and No. ...I think you know what is coming next...the No button changed locations on mouse over and was almost impossible to click.
The students and teacher got a good kick out of it.
The program only required a few lines of user-written code with a simple equation to calculate where to move the button. I don't think any of the other students figured it out, but a few were close.
When I first figured out the bash forkbomb, I thought it was really sweet. So simple, yet neat in what it can do:
:(){ :|:& };:
This is cheating, and not even remotely simple, but I once wrote a shoot'em up in 20 lines of C++, using the Allegro graphics library. No real criteria for what a line was, but it was a bit ago, and it was made purely for fun. It even had crude sound effects.
Here's what it looked like:
20 Lines http://img227.imageshack.us/img227/8770/20linesxx0.png [1]
And here's the code (should compile):
bool inside(int x, int y, int x2, int y2) { return (x>x2&&x<x2+20&&y>y2&&y<y2+10); }
int main() {
BITMAP* buffer;
float px,shotx,shoty,monstars[8],first,rnd,pressed,points = 0, maxp = 0;
unsigned char midi[5] = {0xC0,127,0x90,25,0x54}, plgfx[] = {0,0,0,10,3,10,3,5,6,5,6,10,8,12,10,10,10,5,13,5,13,10,16,10,16,0,13,0,13,2,3,2,3,0,0,0}, mongfx[] = {0,0, 10,5, 20,0, 17,8, 15,6, 10,16, 5,6, 3,8, 0,0};
allegro_init(), set_color_depth(32), set_gfx_mode(GFX_AUTODETECT_WINDOWED,320,240,0,0), install_timer(), install_keyboard(), install_mouse(), buffer = create_bitmap(320,240),srand(time(NULL)),install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT,""),clear_to_color(buffer,makecol32(100,100,255));
while ((pressed=(!key[KEY_Z]&&pressed)?0:pressed)?1:1&&(((shoty=key[KEY_Z]&&shoty<0&&pressed==0?(pressed=1?200:200):first==0?-1:shoty)==200?shotx=px+9:0)==9999?1:1) && 1+(px += key[KEY_LEFT]?-0.1:0 + key[KEY_RIGHT]?0.1:0) && 1+int(px=(px<0?0:(px>228?228:px))) && !key[KEY_ESC]) {
rectfill(buffer,0,0,244,240,makecol32(0,0,0));
for(int i=0;i<8;i++) if (inside(shotx,shoty,i*32,monstars[i])) midi_out(midi,5);
for (int i=0; i<8; monstars[i] += first++>8?(monstars[i]==-100?0:0.02):-100, points = monstars[i]>240?points-1:points, monstars[i]=monstars[i]>240?-100:monstars[i], points = inside(shotx,shoty,i*32,monstars[i])?points+1:points, (monstars[i] = inside(shotx,shoty,i*32,monstars[i])?shoty=-1?-100:-100:monstars[i]), maxp = maxp>points?maxp:points, i++) for (int j=1; j<9; j++) line(buffer,i*32+mongfx[j*2 - 2],monstars[i]+mongfx[j*2-1],i*32+mongfx[j*2],monstars[i]+mongfx[j*2+1],makecol32(255,0,0));
if (int(first)%2000 == 0 && int(rnd=float(rand()%8))) monstars[int(rnd)] = monstars[int(rnd)]==-100?-20:monstars[int(rnd)]; // randomowe pojawianie potworkow
if (shoty>0) rectfill(buffer,shotx,shoty-=0.1,shotx+2,shoty+2,makecol32(0,255,255)); // rysowanie strzalu
for (int i=1; i<18; i++) line(buffer,px+plgfx[i*2 - 2],200-plgfx[i*2-1],px+plgfx[i*2],200-plgfx[i*2+1],makecol32(255,255,0));
textprintf_ex(buffer,font,250,10,makecol32(255,255,255),makecol32(100,100,255),"$: %i ",int(points)*10);
textprintf_ex(buffer,font,250,20,makecol32(255,255,255),makecol32(100,100,255),"$$ %i ",int(maxp)*10);
blit(buffer, screen, 0, 0, 0, 0, 320,240);
}
} END_OF_MAIN()
[1] http://img227.imageshack.us/img227/8770/20linesxx0.pngIn this day and age, JavaScript is an excellent way to show how you can program using some really basic tools e.g. notepad.
jQuery effects are great starting point for anyone wanting to wow their friends!
In this one, just click the white space of the page.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document.body).click(function () {
if ($("#pic").is(":hidden")) {
$("#pic").slideDown("slow");
} else {
$("#pic").slideUp();
}
});
</script>
</head>
<body><img id="pic" src="http://www.smidgy.com/smidgy/images/2007/07/26/lol_cat_icanhascheezburger.jpg"/>
</body>
</html>
One thing you might consider is something like Robocode [1], in which a lot of coding is abstracted away and you basically just tell a robot what to do. A simple 10-line function can make the robot do a great deal, and has a very visual and easy-to-follow result.
Perhaps Robocode itself isn't suited to the task, but this kind of thing is a good way to relate written code to visual actions on the computer, plus it's fun to watch for when you need to give examples.
public class MyFirstJuniorRobot extends JuniorRobot {
public void run() {
setColors(green, black, blue);
// Seesaw forever
while (true) {
ahead(100); // Move ahead 100
turnGunRight(360); // Spin gun around
back(100); // Move back 100
turnGunRight(360); // Spin gun around
}
}
public void onScannedRobot() {
turnGunTo(scannedAngle);
fire(1);
}
public void onHitByBullet() {
turnAheadLeft(100, 90 - hitByBulletBearing);
}
}
[1] http://robocode.sourceforge.net/So one day, I decided that I'd had enough. I would learn piano. Seeing people like Elton John command such mastery of the keyboard assured me that this was what I wanted to do.
Actually learning piano was a huge letdown. Even after completing eight grades of piano lessons, I was still not impressed with how my mental image of playing piano was so different from my original vision of enjoying the activity.
However, what I thoroughly enjoyed was my mere three grades of rudiments of music theory. I learned about the construction of music. I was finally able to step from the world of performing written music to writing my own music. Subsequently, I was able to start playing what I wanted to play.
Don't try to dazzle new programmers, especially young programmers. The whole notion of "less than ten lines of simple code" seems to elicit a mood of "Show me something clever".
You can show a new programmer something clever. You can then teach that same programmer how to replicate this "performance". But this is not what gets them hooked on programming. Teach them the rudiments, and let them synthesize their own clever ten lines of code.
I would show a new programmer the following Python code:
input = open("input.txt", "r")
output = open("output.txt", "w")
for line in input:
edited_line = line
edited_line = edited_line.replace("EDTA", "ethylenediaminetetraacetic acid")
edited_line = edited_line.replace("ATP", "adenosine triphosphate")
output.write(edited_line)
I realize that I don't need to assign line
to edited_line
. However, that's just to keep things clear, and to show that I'm not editing the original document.
In less than ten lines, I've verbosified a document. Of course, also be sure to show the new programmer all the string methods [1] that are available. More importantly, I've showed three fundamentally interesting things I can do: variable assignment, a loop, file IO, and use of the standard library.
I think you'll agree that this code doesn't dazzle. In fact, it's a little boring. No - actually, it's very boring. But show that code to a new programmer and see if that programmer can't repurpose every part of that script to something much more interesting within the week, if not the day. Sure, it'll be distasteful to you (maybe using this script to make a simple HTML parser), but everything else just takes time and experience.
[1] http://docs.python.org/library/stdtypes.html#string-methodsLike most of the other commenters, I started out writing code to solve math problems (or to create graphics for really terrible games that I would design -- things like Indiana Jones versus Zombies).
What really started me (on both math and programming) was going from text based, choose your own adventure style games...to more graphics-based games. I started out coloring graph paper and plotting pixels, until I got into geometry...and discovered how to use equations to plot curves and lines, boxes, etc.
My point is, I could have really gotten into something like processing ( http://processing.org/ ) where a typical program looks something like this:
void setup()
{
size(200, 200);
noStroke();
rectMode(CENTER);
}
void draw()
{
background(51);
fill(255, 204);
rect(mouseX, height/2, mouseY/2+10, mouseY/2+10);
fill(255, 204);
int inverseX = width-mouseX;
int inverseY = height-mouseY;
rect(inverseX, height/2, (inverseY/2)+10, (inverseY/2)+10);
}
To me, this is the "Logo" of the future.
There are easy "hello world" examples that can quickly get someone drawing and changing code and seeing how things break and what weird "accidents" can be created...all the way to more advanced interaction and fractal creation...
You could use a script written with AutoIt [1], which blurs the line between using a traditional application and programming.
E.g. a script which opens notepad and makes their own computer insult them in it and via a message box, and then leaves no trace of its actions:
Run("notepad.exe")
WinWaitActive("Untitled - Notepad")
Send("You smell of human.")
Sleep(10000)
MsgBox(0, "Humans smell bad", "Yuck!")
WinClose("Untitled - Notepad")
WinWaitActive("Notepad", "Do you want to save")
Send("!n")
[1] http://www.autoitscript.com/autoit3/index.shtmlI remember when I first started coding loops always impressed me. You write 5 - 10 lines of code (or less) and hundreds (or however many you specify) lines print out. (I learned first in PHP and Java).
for( int i = 0; i < 200; i++ )
{
System.out.println( i );
}
I think a good place for a student to get started could be Greasemonkey [1]. There are thousands of example scripts on userscripts.org, very good reading material, some of which are very small. Greasemonkey scripts affect web-pages, which the students will already be familiar with using, if not manipulating. Greasemonkey itself offers a very easy way to edit and enable/disable scripts while testing.
As an example, here is the "Google Two Columns" script:
result2 = '<table width="100%" align="center" cellpadding="10" style="font-size:12px">';
gEntry = document.evaluate("//li[@class='g'] | //div[@class='g'] | //li[@class='g w0'] | //li[@class='g s w0']",document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0; i < gEntry.snapshotLength; i++) {
if (i==0) { var sDiv = gEntry.snapshotItem(i).parentNode.parentNode; }
if(i%2 == 0) { result2 += '<tr><td width="50%" valign="top">'+gEntry.snapshotItem(i).innerHTML+'</td>'; }
if(i%2 == 1) { result2 += '<td width="50%" valign="top">'+gEntry.snapshotItem(i).innerHTML+'</td></tr>'; }
}
sDiv.innerHTML = result2+'</table>';
if (document.getElementById('mbEnd') !== null) { document.getElementById('mbEnd').style.display = 'none'; }
[1] http://en.wikipedia.org/wiki/GreasemonkeyThis is a very rudimentary text-based c# program that simulates the spinning action of a slot machine. It doesn't include different odds of winning or cash payouts, but that could be a nice exercise for the students.
Sorry that it is more than 10 lines.
string[] symbols = new[] { "#", "?", "~" }; // The symbols on the reel
Random rand = new Random();
do
{
string a="",b="",c="";
for( int i = 0; i < 20; i++ )
{
Thread.Sleep( 50 + 25 * i ); // slow down more the longer the loop runs
if( i < 10 )
a = symbols[rand.Next( 0, symbols.Length )];
if( i < 15 )
b = symbols[rand.Next( 0, symbols.Length )];
c = symbols[rand.Next( 0, symbols.Length )];
Console.Clear();
Console.WriteLine( "Spin: " + a + b + c );
}
if( a == b && b == c )
Console.WriteLine( "You win. Press enter to play again or type \"exit\" to exit" );
else
Console.WriteLine( "You lose. Press enter to play again or type \"exit\" to exit" );
}
while( Console.ReadLine() != "exit" );
How about a bookmarklet? It would show them how to manipulate something that they use every day (the Internet) without requiring any development tools.
With Tcl [1] you have a simple text editor with a save button in about 12 lines of code (but no open, that would take another 8 lines). It works across all standard platforms:
pack [frame .toolbar] -side top -fill x
pack [button .save -text save -command save] -in .toolbar -side left
pack [scrollbar .vsb -orient vertical -command [list .text yview]] -side right -fill y
pack [text .text -wrap word -yscrollcommand [list .vsb set]] -side left -fill both -expand true
proc save {} {
set filename [tk_getSaveFile]
if {$filename ne ""} {
set f [open $filename w]
puts $f [.text get 1.0 end-1c]
close $f
}
}
I realize the goal was 10 lines, so if you want the to stick to 10 lines or less, a simple text editor without load or save is only two lines. That's not too shabby.
pack [scrollbar .vsb -orient vertical -command [list .text yview]] -side left -fill y
pack [text .text -wrap word -yscrollcommand [list .vsb set]] -side left -fill both -expand true
Execute either of the above blocks of code with "wish filename" on the platform of your choice. Wish comes with most *nix's and the mac but you'll have to install it manually for windows.
To go a step further, that two line script can also be written in python, though it takes eight lines, still under the 10 line goal:
from Tkinter import *
root=Tk()
text = Text(wrap="word")
sb = Scrollbar(orient="vertical", command=text.yview)
text.configure(yscrollcommand=sb.set)
sb.pack(side="right", fill="y")
text.pack(side="left", fill="both", expand=True)
root.mainloop()
[1] http://en.wikipedia.org/wiki/TclIf you can afford the hardware, using an Arduino board + processing will produce some pretty cool things, though it may be a little advanced for people that may not be interested at all in programming.
I wrote about this recently in an article "The Shortest, most useful program I have ever written." [1]
Summary: I wrote a 3 line VB6 app back in 1996 that I still use every single day. Once the exe is dropped in the "Send-to" folder. It lets you right click on a file in explorer and send the full path of that file to the clipboard.
Public Sub Main()
Clipboard.SetText Command$
End Sub
[1] http://softwareplusplus.wordpress.com/2009/05/04/the-shortest-most-useful-program-that-i-have-ever-written/Clipboard.Clear
? It removes all content from the clipboard, even non-text data (e.g. image data). This is generally not what you want at all. - Konrad Rudolph
It's interesting that you mention the Mandelbrot set, as creating fractals with GW-BASIC is what sparked my love of programming back in high school (around 1993). Before we started learning about fractals, we wrote boring standard deviation applications and I still planned to go into journalism.
But once I saw that long, difficult-to-write BASIC program generate "fractal terrain," I was hooked and I never looked back. It changed the way I thought about math, science, computers, and the way I learn.
I hope you find the program that has the same affect on your students.
import wx
app = wx.App()
wx.Frame(None, -1, 'simple.py').Show()
app.MainLoop()
simple.py frame http://zetcode.com/wxpython/images/simple.jpg [2]
[1] http://zetcode.com/wxpython/firststeps/As a supplement to whatever ideas you come up with, I say you should just show them how to do some basic math. Present it as
"now you might think this is easy or complicated... but have you ever been stuck on your math homework?"
Then just pull out an example from someone's book. Most math problems can be solved in 10 lines as it will likely be a simple problem. Then show them how spending 10 minutes to figure it out might be worth the A they might get. It's a long stretch, but you might catch a few who want to spend little to no time doing homework.
This mostly stems from me having wished I had thought of writing a software program back in chemistry... all those quizzes and homeworks would have been 100s...
Edit: To respond to Peter's comment:
Say something like what is the derivative of 3a2. So you could just show a simple function that they can call from the command line:
public int SimpleDerivative(int r, int exponent){
r = r * exponent
exponent =- 1
return (String "{0}a^{1}" where {0} = r, {1} = exponent)
}
exponent -= 1
, and not =-
? - Petrus Theron
I'm sure it'd turn into more than 10 lines of code, but have you considered a form based app where pressing the buttons does things like changing the colour of the background or changes the size of the text? This would show them how interactive programs work. It would also show them that they, as programmer, are in complete control of what the computer (program) does.
Hopefully it would lead them to make suggestions for other things they could change and then onto other things they might want to do.
Many people find gambling exciting and motivating. You could build a blackjack dealer class yourself, exposing an interface. Then, have the kids build a blackjack player class.
You can build a graph for each student's solution showing money versus time to motivate the task.
The beauty of this system is that you can produce incremental solutions over weeks:
The naive solution is to always hit below a certain level. That's maybe 5 lines of code.
A better solution is to look at what the dealer has exposed and adjust your hitting for that.
An even better solution takes into account the actual cards you have-- not just the sum of their values.
The ultimate solution is probably keeping track of the dealt cards over many hands. (The dealer object could make a DealerIsShuffling(int numberofdecks) call on the player object telling the player how many decks there are.)
Another direction this could go is to make the game competitive-- instead of winning money against a dealer, you play against other people's solutions. Of course, you have to rotate who starts hitting first to make things fair.
This bash code lock down your computer. It's called Fork bomb.
:(){ :|:& };:
more info: http://en.wikipedia.org/wiki/Fork_bomb
I taught a class for students with learning disabilities, ages 11-12. We were using Hypercard and they discovered they could record the position of an object (image, box, etc.) as they moved it and play it back (animation). Although this is not coding, they wanted to do more like: delete one of the moves without recording it all over again. I told them they would have to go to the code and change it.
You could see who had a knack for computers/programming when they prefered to do it with code because they had more control.
Doing a complex macro in Excel and then learning what the code is doing could be a gateway to VBA.
Depending on the age group or level of interest, it could be tough to jump straight into code, but it is the end that counts.
I don't have code for this, however it could be abstracted in 10 lines or less. Make the mouse draw a box .. however you move it. when you click (left) the box vanishes, when you click (right) the box changes color.
Students want something practical, something they can hack and customize, something that says this "is not your typical boring class".
Xen's mini-os kernel does this now, but it would require additional abstraction to fit your needs.
You could also try plotting a manderbolt (julia) set while getting the paramaters of the quadratic plane from ambient noise (if the machines have a microphone and sound card) .. their voice generates a fractal. Again, its going to be tricky to do this in 10 lines (in the actual function they edit), but not impossible.
In the real world, you are going to use existing libraries. So I think, 10 lines in main() (or whatever language you use) is more practical. We make what exists work for us, while writing what does not exist or does not work for us. You may as well introduce that concept at the beginning.
Also, lines? int main(void) { unsigned int i; for (i=0; i < 10; i++); return 0; } Perhaps, 10 function calls would be a more realistic goal? This is not an obfuscated code contest.
Good luck!
import sys
for y in range(80):
for x in range(80):
c = complex(x-40.0,y-40.0) / 20.0
z = 0.0
for i in range(100):
z = z*z+c
sys.stdout.write('#' if abs(z) < 2.0 else ' ')
sys.stdout.write('\n')
C program to compute the value of pi:
#include <stdlib.h>
#include <stdio.h>
long a=10000,b,c=2800,d,e,f[2801],g;
int main()
{
for(;b-c;)
f[b++]=a/5;
for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)
for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);
}
Output:
31415926535897932384626433832795028841971693993751058209749445923078164062862089
98628034825342117067982148086513282306647093844609550582231725359408128481117450
28410270193852110555964462294895493038196442881097566593344612847564823378678316
52712019091456485669234603486104543266482133936072602491412737245870066063155881
74881520920962829254091715364367892590360011330530548820466521384146951941511609
43305727036575959195309218611738193261179310511854807446237996274956735188575272
48912279381830119491298336733624406566430860213949463952247371907021798609437027
70539217176293176752384674818467669405132000568127145263560827785771342757789609
17363717872146844090122495343014654958537105079227968925892354201995611212902196
0864034418159813629774771309960518707211349999998372978049951059731732816096318
Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public Sub JohnDenverAnniesSong(): Const E4# = 329.6276: Dim Note&, Frequencies$, Durations$: Frequencies = "iiihfihfffhidadddfhihfffhihiiihfihffihfdadddfhihffhiki": Durations = "aabbbfjaabbbbnaabbbfjaabcapaabbbfjaabbbbnaabbbfjaabcap": For Note = 1 To Len(Frequencies): Beep CLng(E4 * 2 ^ ((AscW(Mid$(Frequencies, Note, 1)) - 96) / 12)), CLng((Asc(Mid$(Durations, Note, 1)) - 96) * 200 - 10): Sleep 10: DoEvents: Next: End Sub
Dump in Excel to run:D
Maybe this is dumb, but I think kids would intuitively grasp it -- the cartoon that started off the whole "What’s your favorite “programmer” cartoon?" at What's your favorite "programmer" cartoon? [1].
E.g. Jason Fox of Foxtrot writes code on the board that does a loop.
Possible point of interest: programming might help you out of trouble some time...
[1] https://stackoverflow.com/questions/84556/whats-your-favorite-programmer-cartoonIt has been fun reading the answers to this question. Once you've achieved the 'wow' factor from the students, illustrate the daisy-chaining affect of the results of one becoming the input of another. Learning how input and output works will illustrate the idea of building blocks and how software grows from lots of little things solving specific problems to larger applications solving bigger problems. If a few 10 line programs can be cool, how cool would it be to then put a bunch of them together? That is non-linear cool.
Take a look at these projects:
Processing is always fun to play with and it creates things that are impressive to all types of people. For instance, a Brownian tree:
int xf = (int) random(width);
int yf = (int) random(height);
int x = (int) random(width);
int y = (int) random(height);
background(0xFF);
while(x != xf || y != yf) {
set(x,y,color(0,0,0));
x = max(0, min(x + -1 + (int) random(3), width - 1) );
y = max(0, min(y + -1 + (int) random(3), height - 1) );
}
10 PRINT "HELLO"
20 GOTO 10
But I was just a kid then. That's also why it was the coolest thing. I don't think you can ever get that same rush from the very first time you programmed a computer. Even if it's as simple as printing "HELLO" to the console infinitely.
You could have your students go to the codeplex IronPython silverlight sample site which includes a < 10 line demonstration of altering a canvas and interacting with the mouse. You can find the silverlight example here [1]
Just seeing code written in a web browser and then executing an altering a small WPF might be intoxicating for some.
[1] http://ironpython.codeplex.com/Wiki/View.aspx?title=SilverlightInteractiveSessionI was blown away by some of the stuff that was shown in the talk Easy AI with Python [1] (video and PDF). For example, teaching a computer how to play Mastermind, solve eight queens, alphametics (those puzzles which are like "9567 + 1085 == 10652" and infer relationships in data. All in the order of 10 lines (possibly with 20 or 30 lines of "behind the scenes" code).
[1] http://us.pycon.org/2009/conference/schedule/event/71/Fibonacci numbers is a cool example to learn recursivity. It shows that recursivity can be simple to write and can be costly to execute. The negative entries case can be introduced later.
int fiboNumber(int index)
{
if (index <= 1)
{
return index;
}
return fiboNumber(index - 1) + fiboNumber(index - 2);
}
Perhaps given these two criteria, Javascript with Processing.js [2] or Flash might be a good start point, though Flash obviously has the downside of requiring.. er... Flash.
Tangential thought: Flash is actually a really great way to teach OOP, since it's much easier to grasp the concepts of objects and classes when you can actually see them!
[1] http://www.codinghorror.com/blog/archives/000669.htmlI remember finding simple loops amazing. Each time I learn a new language I usually throw something like this together:
<?php
$numberOfBottles = 99;
print("<h1>$numberOfBottles Bottles of Beer on the Wall</h1>");
print("$numberOfBottles bottles of beer on the wall,<br />");
print("$numberOfBottles bottles of beer!<br />");
print("Take one down, pass it around,<br />");
for($numberOfBottles--; $numberOfBottles>1; $numberOfBottles--)
{
print("$numberOfBottles bottles of beer on the wall!<br />");
print("<br />");
print("$numberOfBottles bottles of beer on the wall,<br />");
print("$numberOfBottles bottles of beer!<br />");
print("Take one down, pass it around,<br />");
}
print("One last bottle of beer on the wall!");
?>
Maybe some variations with while or foreach loops would be easy too.
When Steve Wozniak [1] built his first Apple II he liked to show it off with a Breakout [2] game in Apple Basic, typed in on the spot. I think it actually was around 10 lines; I wish I had it to paste in here. You could probably also do it in a system like Processing [3].
[1] http://en.wikipedia.org/wiki/Steve_WozniakIf you're teaching engineers, this bit of Prolog might get their attention:
d(x,x,1).
d(C,x,0):-number(C).
d(C*x,x,C):-number(C).
d(-U, X, -DU) :- d(U, X, DU).
d( U + V, x, RU + RV ):-d(U,x,RU), d(V,x,RV).
d( U - V, x, RU - RV ):-d(U,x,RU), d(V,x,RV).
d(U * V,x, U * DV + V * DU):- d(U,x,DU), d(V,x,DV).
d(U^N, x, N*U^(N-1)*DU) :- integer(N), d(U, x, DU).
Just write down the rules, and you have a program that can do all of first semester calculus, in 8 lines of code.
I think any sort of shell script which can do something useful is a great way to show someone the power of programming. Being able to spend 10-20 minutes on a small script that will automate another task and save you countless hours is very impressive, imo.
For example, I once wrote a simple Perl script to convert mp3 files in one directory to another format and them burn them to a cd. You invoke the script with the path to a directory of MP3's and it burns the cd. At least I was impressed at the time.
Logo [1] is always a terrific starting point.
Brian Harvey's UCBLogo page has this short example [2]:
[1] http://en.wikipedia.org/wiki/Logo_%28programming_language%29Here is a short but complete program in Berkeley Logo:
to choices :menu [:sofar []] if emptyp :menu [print :sofar stop] foreach first :menu [(choices butfirst :menu sentence :sofar ?)] end
And here's how you use it. You type
choices [[small medium large] [vanilla [ultra chocolate] lychee [rum raisin] ginger] [cone cup]]
and Logo replies
small vanilla cone small vanilla cup small ultra chocolate cone small ultra chocolate cup small lychee cone small lychee cup small rum raisin cone small rum raisin cup small ginger cone small ginger cup medium vanilla cone medium vanilla cup medium ultra chocolate cone medium ultra chocolate cup medium lychee cone medium lychee cup medium rum raisin cone medium rum raisin cup medium ginger cone medium ginger cup large vanilla cone large vanilla cup large ultra chocolate cone large ultra chocolate cup large lychee cone large lychee cup large rum raisin cone large rum raisin cup large ginger cone large ginger cupThe program doesn't have anything about the size of the menu built in. You can use any number of categories, and any number of possibilities in each category. Let's see you do that in four lines of Java!
I think this question is really good idea. I had a lot of sucky teachers, and the best one where obviously the guys with the will to show off a little bit.
There are plenty of code you can show them. The first that comes to my mind is Ed Felten [1]'s TinyP2P source code :
import sys, os, SimpleXMLRPCServer, xmlrpclib, re, hmac # (C) 2004, E.W. Felten
ar,pw,res = (sys.argv,lambda u:hmac.new(sys.argv[1],u).hexdigest(),re.search)
pxy,xs = (xmlrpclib.ServerProxy,SimpleXMLRPCServer.SimpleXMLRPCServer)
def ls(p=""):return filter(lambda n:(p=="")or res(p,n),os.listdir(os.getcwd()))
if ar[2]!="client": # license: http://creativecommons.org/licenses/by-nc-sa/2.0
myU,prs,srv = ("http://"+ar[3]+":"+ar[4], ar[5:],lambda x:x.serve_forever())
def pr(x=[]): return ([(y in prs) or prs.append(y) for y in x] or 1) and prs
def c(n): return ((lambda f: (f.read(), f.close()))(file(n)))[0]
f=lambda p,n,a:(p==pw(myU))and(((n==0)and pr(a))or((n==1)and [ls(a)])or c(a))
def aug(u): return ((u==myU) and pr()) or pr(pxy(u).f(pw(u),0,pr([myU])))
pr() and [aug(s) for s in aug(pr()[0])]
(lambda sv:sv.register_function(f,"f") or srv(sv))(xs((ar[3],int(ar[4]))))
for url in pxy(ar[3]).f(pw(ar[3]),0,[]):
for fn in filter(lambda n:not n in ls(), (pxy(url).f(pw(url),1,ar[4]))[0]):
(lambda fi:fi.write(pxy(url).f(pw(url),2,fn)) or fi.close())(file(fn,"wc"))
Ok, it's 5 lines more than you "ten" limit, but still a fully functionnal Peer 2 Peer app, thansk to Python.
TinyP2P can be run as a server:
python tinyp2p.py password server hostname portnum [otherurl]
and a client:
python tinyp2p.py password client serverurl pattern
Then of course, story telling is very important. For such a purpose, 99 bottles of beer [2] is a really good start.
You can then pick up several example of funcky code like :
the famous Python one-liner :
print("".join(map(lambda x: x and "%s%d bottle%s of beer on the wall, %d bottle%s of beer...\nTake one down, pass it around.\n"%(x<99 and "%d bottles of beer on the wall.\n\n"%x or "\n", x, x>1 and "s" or " ", x, x>1 and "s" or " ";) or "No bottles of beer on the wall.\n\nNo more bottles of beer...\nGo to the store and buy some more...\n99 bottles of beer.", range(99,-1,-1))))
the cheaty Python version (cool for student cause it shows network features) :
import re, urllib
print re.sub('</p>', '', re.sub('<br>|<p>|<br/> |<br/>','\n', re.sub('No', '\nNo',
urllib.URLopener().open('http://www.99-bottles-of-beer.net/lyrics.html').read()[3516:16297])))
Eventually I'll follow previous advices and show some Javascript because it's very visual. The jQuery UI Demo web site [3] is plenty of nice widgets demo including snippets. A calendar [4] in few lines :
<script type="text/javascript">
$(function() {
$("#datepicker").datepicker();
});
</script>
<div class="demo">
<p>Date: <input id="datepicker" type="text"></p>
</div>
Bookmarklets have a lot of sex appeal too. Readibility [5] is quite interesting :
function() {
readStyle='style-newspaper';readSize='size-large';
readMargin='margin-wide';
_readability_script=document.createElement('SCRIPT');
_readability_script.type='text/javascript';
_readability_script.src='http://lab.arc90.com/experiments/readability/js/readability.js?x='+(Math.random());
document.getElementsByTagName('head')[0].appendChild(_readability_script);
_readability_css=document.createElement('LINK');
_readability_css.rel='stylesheet';
_readability_css.href='http://lab.arc90.com/experiments/readability/css/readability.css';
_readability_css.type='text/css';_readability_css.media='screen';
document.getElementsByTagName('head')[0].appendChild(_readability_css);
_readability_print_css=document.createElement('LINK');
_readability_print_css.rel='stylesheet';_readability_print_css.href='http://lab.arc90.com/experiments/readability/css/readability-print.css';
_readability_print_css.media='print';
_readability_print_css.type='text/css';
document.getElementsByTagName('head')[0].appendChild(_readability_print_css);
}
[1] http://www.freedom-to-tinker.com/print"".join(("%s%s on the wall, %s.\n"+(i>0 and"Take 1 down and pass it around, "or"Go to the store and buy some more, 99 bottles of beer on the wall."))%(i<99 and"%s on the wall.\n\n"or"","%s","%s")%((2+(i<99))*("%s bottle%s of beer"%(i or"No more",i!=1 and"s"or""),))for i in range(99,-1,-1))
Note that this follows the format given at 99-bottles-of-beer.net/lyrics.html - Ponkadoodle
Try having your students program a Magic 8ball. A basic 8ball answering "yes" or "no" could probably be programmed in less than 10 lines of code, and it can be expanded incrementally in any number of ways:
A magic 8ball is something most people can relate to, and it's an introduction to basic strings, floats/ints, IO, CLI, boolean and RNG's, using only the simplest tools. And it's simple, (somewhat) fun, and can easily be expanded. Depending on you're approach, you could make the programming object-oriented at once, with class 8ball(), class YesAnswer() and whatnot.
Good luck ;-)
This PHP code only works on a Mac through the command-line, but it's very useful when everyone wants to play Twister [1]
$lr = array('left', 'right');
$hf = array('hand', 'foot');
$colour = array('red', 'yellow', 'blue', 'green');
while(true) {
$a = $lr[array_rand($lr)];
$b = $hf[array_rand($hf)];
$c = $colour[array_rand($colour)];
system("say $a $b $c");
sleep(5);
}
[1] http://en.wikipedia.org/wiki/Twister_(game)Here is a program in the language of A-Prolog that computes the N coloring of a graph ("c" denotes colors, "v" denotes vertices, and "e" denotes edges).
c(1..n).
1 {color(X,I) : c(I)} 1 :- v(X).
:- color(X,I), color(Y,I), e(X,Y), c(I).
On a side note, the way I got my students excited last semester was to tell them a story. It went something along the lines of: "Picture a triangle. It's a purely mathematical object, no real triangles exists. We can reason about them, discover their properties, and then apply those properties towards real world solutions. An algorithm is also a purely mathematical object. Programming is a form of magic however. We can take a mathematical object, describe it a language, and lo and behold it can manipulate the physical world. Programming is a unique discipline that bridges these two worlds."
from Andrew Cooke's Malbolge: Hello World [1]
let them try this in Malbolge:
(=<`$9]7<5YXz7wT.3,+O/o'K%$H"'~D|#z@b=`{^Lx8%$Xmrkpohm-kNi;gsedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543s+O<oLm
that's "Hello World" in the most difficult programming language in the whole world that took two years to find :)
They can go to Lou Scheffer's Malbolge page after [2] :)
of course you can go the No. 1 (!!!) 99 Bottles of Beer Program in the World by Hisashi Iizawa (it's a ONE LINER!) [3] and here's a pdf by Masahiko Sakai on Malbolge [4]
[1] http://acooke.org/malbolge.htmlMost of these answers use an API of some kind, which sort of breaks the 10 lines of code requirement. Each API call can be hundred of lines of code. The original question says to use 'Simple Code'. This to me means no API calls. What kind of answers can we come up with that just uses this definition of 'simple code'?
I think some cool expiriments in Python with NodeBox [1] 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.
[1] http://www.nodebox.nethmm, I remember making snowflakes and fire in QBasic [1] 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.
[1] http://en.wikipedia.org/wiki/QBasicWhen I was a kid this was the coolest thing ever:
10 PRINT "BEDWYR "
20 GOTO 10
I guess it won't cut it much these days ;)
In WPF, you can write a fully functional Thumbnail View in a few XAML lines:
<ListBox ItemsSource={Binding MyItems}
ScrollViewer.HorizontalScrollBarVisibility="Hidden">
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source={Binding FullPath} Width="50" />
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate><WrapPanel /></ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
This is, assuming you have a MyItems
collection of items that contain a FullPath
property that points to image files.
The magic comes from the ItemTemplate
that transforms each list box item into an image, and the ItemsPanelTemplate
that changes the default vertical stack panel to a wrap panel.
First To get maximum attention at minimum time, you'll want to use a high-level language. probably you'll want to show 3D [1].
I'd go with Opengl [2] - 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 [3], or maybe even a more advanced lesson. it's quite impressive, and not too complicated.
Also you may want to check Alice [4] which contains 3d and was designed to teach..
[1] http://en.wikipedia.org/wiki/File:Glasses_800_edit.pngSomething 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
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:
The modification itself shouldn't take too many lines of code, but the fact that it works is just amazing.
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...
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();
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);
}
}
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
A basic grep application in Ruby/Python/Perl.
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/
^_^
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.
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
10 Print "Mohan"
20 Goto 10
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)
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
From my answer [1] to How do I loop through every 4th pixel in every 4th row, using Python? [2]:
#!/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 [3]:
# 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()
[1] https://stackoverflow.com/questions/2376505/how-do-i-loop-through-every-4th-pixel-in-every-4th-row-using-python/2377061#2377061I created Advanced Calculator With 4 Lines of Code [1]
[1] http://sarfraznawaz.wordpress.com/2010/02/28/creating-advanced-calculator-with-4-lines-of-code/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
My first program is somewhat similar to one already mentioned here [1], but my is one line shorter and much more polite:
10 PRINT "What is your name?"
20 INPUT A$
30 PRINT "Thanks"
[1] https://stackoverflow.com/questions/811074/what-is-the-coolest-thing-you-can-do-in-10-lines-of-simple-code-help-me-inspire/811081#811081At 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.
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);
}
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.
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?
Messing around with cookies.
Its cookies! Kids loooovvve cookies!
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;
}