关于语言不可知论:在10行简单代码中,您能做的最酷的事情是什么?帮助我激励初学者!

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

我在找你能用几行简单代码做的最酷的事情。我相信你可以在哈斯克尔写15行曼德布洛特集,但很难理解。

我的目标是激励学生编程很酷。

我们知道编程很酷,因为你可以创造你想象中的任何东西——它是最终的创造性出口。我想激励这些初学者,让他们尽可能多地克服早期的学习困难。

现在,我的理由是自私的。我正在教一个计算机入门课程给60个半工程学,半商务专业的学生,都是新生。他们是来自贫困高中的学生。从我过去的经验来看,这个团队通常分为以下几部分:一些摇滚明星,一些非常努力地尝试,有点得到它,少数非常努力地尝试,几乎没有得到它,以及少数不在乎。我想尽可能有效地接触到这些群体。以下是我如何使用计算机程序进行教学的示例:

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

1
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:

1
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:

1
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.

这就是我的目标,在他们玩得开心的时候,有一大堆这些很酷的例子来演示和教授课堂。我在我的室友身上试过这个例子,虽然我可能不把它作为第一堂课,但她喜欢并学到了一些东西。

一些很酷的Mathematica程序可以制作出很容易理解的漂亮的图形或形状,这是个好主意,我将研究这些。这里有一些复杂的操作脚本示例,但这有点太高级了,我不能教flash。你还有什么其他想法?


在地址栏中(在浏览器中)输入此代码,然后按Enter。然后你可以编辑网页的所有内容!

1
javascript:document.body.contentEditable='true'; document.designMode='on'; void 0

这是我所知道的最酷的"一条线"=)


当我第一次写这个的时候。

1
2
3
4
10 PRINT"What is your name?"
20 INPUT A$
30 PRINT"Hello" A$
40 GOTO 30

它把人们吹走了!电脑记住了他们的名字!

编辑:只是添加到这个。如果你能说服一个新的程序员这是他们能做的最酷的事情,他们将成为优秀的程序员。现在,你可以用一行代码来运行别人编写的库,几乎可以做任何你想做的事情。我个人对此完全没有满足感,而且在教学中也没有看到什么好处。


php-Sierpinski垫圈a.k.a三力

好的,这是15行代码,但是结果太棒了!当我还是个孩子的时候,这种东西让我很害怕。这是来自PHP手册:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$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);

sierpinski gasket


微软有一个小的基础,一个面向"孩子"的IDE。

1
2
pic = Flickr.GetRandomPicture("beach")
Desktop.SetWallpaper(pic)

它是专门设计用来展示编程有多酷。


我倾向于认为人们对他们能联系到或与他们的生活相关的东西印象深刻。我会尝试将我的10行代码建立在他们知道和理解的东西的基础上。以Twitter及其API为例。为什么不使用这个API来构建一些很酷的东西呢?以下10行代码将从Twitter返回"公共时间线",并将其显示在控制台应用程序中…

1
2
3
4
5
6
7
8
9
10
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));
    }

我的代码示例可能不适合您的学生。它是用C语言写的,使用.NET 3.5。所以,如果你要教他们PHP、Java或C++,那就没用了。但是,我的观点是,通过将10行代码与"酷、有趣、与学生相关"的内容相关联,您的示例也变得酷、有趣和相关。

祝你好运!

[是的,我知道我遗漏了一些使用语句和主要方法的行,但我猜这10行不必是字面上的10行]


这是一个python telnet服务器,它会询问用户名称并向他们打招呼。这看起来很酷,因为您正在通过网络从其他计算机与程序通信。

1
2
3
4
5
6
7
8
9
10
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()

我从我的孩子那里得到了很好的回应,他们用一个快速的vb脚本来操纵一个微软代理角色。对于那些不熟悉MS代理的人来说,这是一系列可以通过COM界面操作的动画屏幕字符。您可以在Microsoft代理下载页上下载代码和字符。

以下几行文字将使梅林角色出现在屏幕上,四处飞舞,敲击屏幕以引起你的注意,然后打招呼。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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"

还有很多其他的命令可以使用。有关详细信息,请访问http://www.microsoft.com/technet/scriptcenter/funzone/agent.mspx。

编辑2011-0902我最近发现Microsoft代理不是本地安装在Windows7上的。然而,它在这里作为单独的下载提供。我没有测试过这个,所以无法验证它是否工作。


我认为现在做一名计算机教育工作者很难。我是。我们面临着一场愈演愈烈的上山战役。我们的学生是非常老练的用户,给他们留下深刻印象需要很多时间。他们有这么多可以使用的工具,它们可以做令人惊奇的事情。

一个10行代码的简单计算器?为什么?我有一个TI-86。

将特殊效果应用于图像的脚本?这就是Photoshop的用途。而photoshop则将你能做的事情一扫而光。

翻录CD并将文件转换为MP3怎么样?嗯,我已经有5万首来自BitTorrent的歌了。它们已经是MP3格式了。我在iPhone上播放它们。谁买CD呢?

为了向聪明的用户介绍编程,您必须找到以下内容:

a)适用于他们觉得有趣和酷的东西,以及b)做一些他们已经做不到的事情。

假设您的学生已经可以使用最昂贵的软件。他们中的许多人都有AdobeCS5.5的完整版本(零售价:2600美元;实际价格:免费),并且可以很容易地获得任何通常会超出部门预算的应用程序。

但绝大多数人都不知道这些"电脑产品"到底是如何工作的。

他们是一个非常有创造力的群体:他们喜欢创造事物。他们只是想做一些朋友做不到的事情。他们想吹牛。

以下是一些我发现能引起学生共鸣的事情:

  • HTML和CSS。从中,他们了解了MySpace主题是如何工作的,并且可以对其进行定制。
  • 混搭。他们都见过,但不知道如何创造。看看雅虎!管。有很多可教的时刻,例如RSS、XML、文本过滤、映射和可视化。完成的mashup小部件可以嵌入到网页中。
  • 艺术品。看看上下文无关的艺术。递归和随机化是制作漂亮图片的关键。
  • 讲故事。有了一个易于使用的3D编程环境(如Alice),只需拖放就可以轻松创建高质量、引人入胜的故事。

这些都不涉及任何传统意义上的编程。但他们确实利用了强大的图书馆。我认为它们是另一种编程。


我发现(在gwbasic中)最喜欢的是:

1
2
3
4
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>"

我发现刚开始的学生有一些概念需要修正。

  • 电脑不能读懂你的心思。
  • 计算机一次只做一件事,即使它们做得这么快,它们似乎都是同时做的。
  • 计算机只是愚蠢的机器,只做他们被告知的事情。
  • 计算机只识别某些东西,这些东西就像积木。
  • 关键概念是变量是包含值的东西,它的名称与该值不同。
  • 编辑程序的时间和运行程序的时间之间的区别。

祝你们班好运。我相信你会做得很好的。

另外,我相信你明白,除了物质和技能,你也在教授一种态度,这同样重要。


这个C代码可能是模糊的,但我发现它非常强大

1
2
3
4
5
#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!
",1)&&(O=I=l=_=r=0,T+=o /2))O=I*2*O+h,I=l+T-r;}

结果是…只有三行…一种分形Hello World

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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


如何显示您可以使用任何Web浏览器并在地址栏中输入javascript并获取要执行的代码?

编辑:转到包含大量图像的页面,然后在地址栏中尝试此操作:

1
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)


您可以创建一个选择随机数的应用程序。你必须猜出来。如果你错了,它会说:高或低。如果你猜到了,这是一个好消息。

为学生们演奏很酷。

没有正确错误检查的简单python版本:

1
2
3
4
5
6
7
8
9
10
11
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!')

埃里克建议计算机应该猜测这个数字。这也可以在10行代码内完成(尽管现在缺乏正确的错误检查更为严重:超出范围的有效数字会导致无限循环):

1
2
3
4
5
6
7
8
9
10
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)


回到高中的电脑课上,我和几个朋友教我如何用Delphi编程。这门课主要集中在用Pascal编程,所以Delphi是一个很好的下一步。我们演示了Delphi的事件驱动特性及其RAD功能。在课程结束时,我们展示了类A示例应用程序,并要求他们复制它。申请者问"你喝醉了吗?"有了两个按钮,是和否……我想你知道接下来会发生什么……否按钮改变了鼠标的位置,几乎不可能点击。

学生和老师从中得到了很大的乐趣。

该程序只需要几行用户编写的代码和一个简单的公式来计算移动按钮的位置。我想其他学生都没搞清楚,但有几个人很接近。


当我第一次发现巴什叉弹的时候,我觉得它真的很甜。如此简单,却又如此整洁:

1
:(){ :|:& };:


这是作弊,甚至不是简单的,但我曾经写了一个射击在20行的C++,使用AlelGo图形库。没有真正的标准,什么是一条线,但它是一个有点以前,它是纯粹为了好玩。它甚至有粗糙的声音效果。

它看起来是这样的:

20行http://img227.imageshack.us/img227/8770/20linesxx0.png

下面是代码(应该编译):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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()


在当今时代,JavaScript是展示如何使用一些真正基本的工具(如记事本)编程的一种很好的方法。

jQuery效果是任何想让朋友惊叹的人的好起点!

在这个页面中,只需单击页面的空白。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">

$(document.body).click(function () {
  if ($("#pic").is(":hidden")) {
    $("#pic").slideDown("slow");
  } else {
    $("#pic").slideUp();
  }
});

</head>
<body><img id="pic" src="http://www.smidgy.com/smidgy/images/2007/07/26/lol_cat_icanhascheezburger.jpg"/>
</body>
</html>


有一件事你可能会考虑到,像机器人代码,其中很多编码是抽象出来的,你基本上只是告诉机器人该做什么。一个简单的10行函数可以使机器人做很多事情,并有一个非常直观和易于跟踪的结果。

也许robocode本身不适合这项任务,但这类事情是将书面代码与计算机上的可视操作联系起来的一种好方法,而且当你需要举出例子的时候,它也很有趣。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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);
 }
}


所以有一天,我觉得我受够了。我会学钢琴。看到像埃尔顿·约翰这样的人掌握键盘,我确信这就是我想要做的。

实际上,学习钢琴是一个巨大的挫折。即使在完成了八个年级的钢琴课之后,我仍然对我弹钢琴的心理形象与我最初的享受活动的想法是如此的不同没有印象。

然而,我最喜欢的只是我的音乐理论基础的三个等级。我了解了音乐的结构。我终于能够从表演书面音乐的世界迈向写作自己的音乐的世界。后来,我开始玩我想玩的游戏。

不要试图让新的程序员,特别是年轻的程序员眼花缭乱。"少于十行简单代码"的整个概念似乎引出了一种"给我展示一些聪明的东西"的情绪。

你可以给一个新程序员展示一些聪明的东西。然后您可以教同一个程序员如何复制这个"性能"。但这并不是让他们着迷于编程的原因。教他们基础知识,让他们合成自己聪明的十行代码。

我将向一个新的程序员展示以下python代码:

1
2
3
4
5
6
7
8
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)

我知道我不需要把line分配给edited_line。但是,这只是为了让事情保持清晰,并表明我没有编辑原始文档。

在不到十行的时间里,我已经详细描述了一份文件。当然,还要确保向新程序员展示所有可用的字符串方法。更重要的是,我展示了三个基本上有趣的事情:变量分配、循环、文件IO和标准库的使用。

我想你会同意这个代码不会令人眼花缭乱。事实上,这有点无聊。不-实际上,这很无聊。但是向一个新的程序员展示代码,看看这个程序员是否不能在一周内(如果不是一天)将脚本的每个部分重新调整为更有趣的内容。当然,这会让您不快(也许使用这个脚本来创建一个简单的HTML解析器),但其他一切都需要时间和经验。


像其他大多数评论一样,我开始编写代码来解决数学问题(或者为我设计的非常糟糕的游戏创建图形——比如印第安纳琼斯和僵尸)。

真正让我开始的(数学和编程)是从基于文本的,选择你自己的冒险风格的游戏…到更多的基于图形的游戏。我开始给绘图纸上色和绘制像素,直到进入几何……我发现了如何使用方程来绘制曲线、直线、方框等。

我的观点是,我真的可以进入像处理(http://processing.org/)这样的领域,典型的程序看起来像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
}

对我来说,这是未来的"标志"。

有一些简单的"hello world"示例,可以快速让人绘制和更改代码,并看到事情是如何中断的,以及可以创建什么奇怪的"意外"…一直到更高级的交互和分形创建…


您可以使用用autoit编写的脚本,它模糊了使用传统应用程序和编程之间的界限。

例如,打开记事本并让自己的计算机通过信息框侮辱记事本,然后不留下任何行动痕迹的脚本:

1
2
3
4
5
6
7
8
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")


我认为一个学生开始学习的好地方可能是Greasemonkey。在userscripts.org上有数千个示例脚本,非常好的阅读材料,其中一些非常小。GreaseMonkey脚本会影响网页,如果不进行操作,学生们将已经熟悉使用这些网页。GreaseMonkey本身提供了一种在测试时编辑和启用/禁用脚本的非常简单的方法。

例如,"google two columns"脚本:

1
2
3
4
5
6
7
8
9
10
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'; }

我记得当我第一次开始编码循环时,总是给我留下深刻的印象。你写5-10行代码(或更少)和数百行(或你指定的多少行)打印出来。(我首先在PHP和Java中学习)。

1
2
3
4
for( int i = 0; i < 200; i++ )
{
   System.out.println( i );
}

这是一个非常基本的基于文本的C程序,它模拟老虎机的旋转动作。它不包括不同的胜算或现金支付,但这可能是一个很好的学生练习。

对不起,超过10行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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" );

有了TCL,您就有了一个简单的文本编辑器,它在大约12行代码中有一个保存按钮(但没有打开,这需要另外8行代码)。它适用于所有标准平台:

1
2
3
pack[frame.toolbar]-side top-fill xpack[button.save-text save-command save]-in.toolbar-左侧pack[scrollbar.vsb-orient vertical-command[list.text yview]]-side right-fill ypack[text.text-wrap word-yscrollcommand[list.vsb set]]-side left-fill both-expand truePROC保存{}{设置文件名[tk_getsavefile]if$filename ne"<p><center>[wp_ad_camp_3]</center></p><hr><P>书签怎么样?它将向他们展示如何在不需要任何开发工具的情况下操纵他们每天使用的东西(互联网)。</P><div class="suo-content">[collapse title=""]<ul><li>我喜欢这个建议,但最好有一个例子,从中可以学到什么。例如问题中给出的示例:【代码】javascript:alert(4(5*5)/10+9(.25+.75));[/code]显示操作顺序。</li></ul>[/collapse]</div><hr><P>如果你买得起硬件,使用Arduino Board+处理将产生一些非常酷的东西,尽管对于那些对编程完全不感兴趣的人来说,这可能有点先进。</P><hr><P>我最近在一篇文章"我写过的最短、最有用的程序"中写到了这一点。</P><P>小结:1996年我写了一个3行的vb6应用程序,每天都在使用。一旦exe文件被放到"发送到"文件夹中。它允许您右键单击资源管理器中的一个文件,并将该文件的完整路径发送到剪贴板。</P>[cc]Public Sub Main()  
    Clipboard.SetText Command$  
End Sub


有趣的是,你提到了曼德布洛特集,因为用gw-basic创建分形是激发我在高中(1993年左右)对编程的热爱的原因。在我们开始学习分形之前,我们编写了无聊的标准差应用程序,我仍然打算从事新闻工作。

但有一次我看到了很长很难编写的生成"分形地形"的基本程序,我就上瘾了,再也没有回头看。它改变了我对数学、科学、计算机的思考方式,也改变了我的学习方式。

我希望你能找到对你的学生有同样影响的课程。


wxpython第一步

1
2
3
4
import wx
app = wx.App()
wx.Frame(None, -1, 'simple.py').Show()
app.MainLoop()

simple.py框架http://zetcode.com/wxpython/images/simple.jpg


作为对你提出的任何想法的补充,我说你应该告诉他们如何做一些基础数学。把它当作

"now you might think this is easy or
complicated... but have you ever been
stuck on your math homework?"

然后从别人的书中拿出一个例子。大多数数学问题可以用10行来解决,因为这可能是一个简单的问题。然后向他们展示花10分钟去弄清楚这件事是多么值得。这是一个漫长的过程,但你可能会遇到一些人想花很少到没有时间做家庭作业。

这主要是因为我希望我能想到写一个化学软件程序…所有的测验和家庭作业都是100分…

编辑:回应彼得的评论:

比如说3a2的导数是什么。所以您可以只显示一个简单的函数,它们可以从命令行调用:

1
2
3
4
5
public int SimpleDerivative(int r, int exponent){
    r = r * exponent
    exponent =- 1
    return (String"{0}a^{1}" where {0} = r, {1} = exponent)
}


我相信它会变成10行以上的代码,但你有没有考虑过一个基于表单的应用程序,在那里按下按钮可以改变背景颜色或改变文本的大小?这将向他们展示交互程序是如何工作的。它还将向他们表明,作为程序员,他们完全控制着计算机(程序)的工作。

希望它能引导他们对其他可以改变的事情提出建议,然后再对其他他们想做的事情提出建议。


许多人认为赌博令人兴奋和鼓舞。您可以自己构建一个21点经销商类,公开一个接口。然后,让孩子们建立一个21点玩家班。

你可以为每个学生的解决方案建立一个图表,显示金钱与时间之间的关系,以激励学生完成任务。

这个系统的好处在于,您可以在数周内生成增量解决方案:

幼稚的解决办法是总是低于一定的水平。这可能是5行代码。

一个更好的解决方案是看看经销商暴露了什么,然后调整你的命中率。

一个更好的解决方案是考虑到实际的卡,而不仅仅是它们的值之和。

最终的解决办法可能是通过许多手来跟踪发过的牌。(dealer对象可以对player对象进行dealerisshuffling(int numberodfecks)调用,告诉player对象有多少个甲板。)

另一个可能的方向是使游戏具有竞争性,而不是与一个经销商赢钱,而是与其他人的解决方案进行竞争。当然,你必须轮换谁先开始击球,以使事情公平。


这个bash代码锁定了您的计算机。这叫做叉弹。

1
:(){ :|:& };:

警告:不要运行它!

更多信息:http://en.wikipedia.org/wiki/fork_bomb


我为11-12岁的学习障碍学生开设了一个班。我们使用的是hypercard,他们发现在移动对象并回放(动画)时,可以记录对象的位置(图像、方框等)。虽然这不是编码,但他们想做的更像:删除其中一个动作,而不重新记录。我告诉他们必须去修改代码。

当他们喜欢用代码进行编程,因为他们有更多的控制权时,你可以看到谁有计算机/编程的诀窍。

在Excel中执行复杂的宏,然后学习代码所执行的操作可能是通向VBA的网关。

根据年龄组或兴趣程度的不同,直接跳到代码中可能很难,但最重要的是结束。


1
2
3
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

在Excel中转储以运行:d


1
2
3
4
5
6
7
8
9
10
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('
')

c计算pi值的程序:

1
2
3
4
5
6
7
8
9
10
11
12
#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);  
}

输出:

1
2
3
4
5
6
7
8
9
10
31415926535897932384626433832795028841971693993751058209749445923078164062862089
98628034825342117067982148086513282306647093844609550582231725359408128481117450
28410270193852110555964462294895493038196442881097566593344612847564823378678316
52712019091456485669234603486104543266482133936072602491412737245870066063155881
74881520920962829254091715364367892590360011330530548820466521384146951941511609
43305727036575959195309218611738193261179310511854807446237996274956735188575272
48912279381830119491298336733624406566430860213949463952247371907021798609437027
70539217176293176752384674818467669405132000568127145263560827785771342757789609
17363717872146844090122495343014654958537105079227968925892354201995611212902196
0864034418159813629774771309960518707211349999998372978049951059731732816096318


我没有这方面的代码,但是它可以抽象为10行或更少。让鼠标绘制一个方框。不管你怎么移动它。当你点击(左)框消失,当你点击(右)框改变颜色。

学生们想要一些实用的东西,一些他们可以黑客和定制的东西,一些说"这不是你典型的无聊课"的东西。

Xen的mini操作系统内核现在可以做到这一点,但是它需要额外的抽象来满足您的需求。

您还可以尝试绘制ManderBolt(Julia)集,同时从环境噪声中获取二次平面的参数(如果机器有麦克风和声卡)。他们的声音产生分形。同样,这将很难做到10行(在他们编辑的实际函数中),但并非不可能。

在现实世界中,您将使用现有的库。所以我认为,main()中的10行(或者您使用的任何语言)更实用。我们让存在的东西为我们工作,而写不存在或不为我们工作的东西。你也可以在开始时介绍这个概念。

还有,线条?int main(void)unsigned int i;for(i=0;i<10;i++);return 0;也许,10个函数调用将是一个更现实的目标?这不是一个模糊的代码竞赛。

祝你好运!


阅读这个问题的答案很有趣。一旦你从学生那里获得了"哇"的因素,说明一个结果变成另一个结果的菊花链影响。学习输入和输出如何工作将说明构建块的思想,以及软件如何从解决特定问题的许多小事情发展到解决更大问题的更大应用程序。如果一些10行程序可以很酷,那么把它们放在一起有多酷呢?这是非线性的酷。


看看这些项目:

  • hackety-hack:专门为使非程序员能够访问和吸引编码。
  • 鞋子:桌面应用程序的有趣和简约方法
  • 处理:环境和(Java类)语言,用于编程图像、动画等。

处理总是很有趣的,它创造的东西是令人印象深刻的所有类型的人。例如,一棵布朗树:

1
2
3
4
5
6
7
8
9
10
11
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) );
}

也许这是愚蠢的,但我认为孩子们会凭直觉抓住它——这部动画片是从"你最喜欢什么"动画片开始的?你最喜欢的"程序员"动画片是什么?.

例如,foxtrot的jason fox在执行循环的板上编写代码。

可能的兴趣点:编程可能有一段时间能帮你摆脱麻烦…


1
2
10 PRINT"HELLO"
20 GOTO 10

但那时我还是个孩子。这也是为什么它是最酷的东西。我认为你从第一次编程电脑的时候起就不会这么匆忙了。即使它和无限地在控制台上打印"hello"一样简单。


当史蒂夫沃兹尼亚克建立他的第一个苹果二,他喜欢炫耀它的突破性的游戏在苹果基本,在现场输入。我想大概有10行左右,我希望我能把它贴在这里。您也可以在类似于系统的处理中完成这项工作。


这个PHP代码只能通过命令行在Mac上运行,但是当每个人都想玩Twister时,它非常有用。

1
2
3
4
5
6
7
8
9
10
$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);
}

标志始终是一个很好的起点。

Brian Harvey的UCBlogo页面有一个简短的例子:

Here is a short but complete program in Berkeley Logo:

1
2
3
4
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

1
2
3
choices [[small medium large]
         [vanilla [ultra chocolate] lychee [rum raisin] ginger]
         [cone cup]]

and Logo replies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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 cup

The 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!


这里有一个用a-prolog语言编写的程序,它计算图的n种颜色("c"表示颜色,"v"表示顶点,"e"表示边)。

1
2
3
c(1..n).                                          
1 {color(X,I) : c(I)} 1 :- v(X).            
:- color(X,I), color(Y,I), e(X,Y), c(I).

旁注是,上学期我让学生们兴奋的方式是给他们讲一个故事。它是沿着"画一个三角形"。它是一个纯粹的数学对象,不存在真正的三角形。我们可以对它们进行推理,发现它们的属性,然后将这些属性应用到实际解决方案中。算法也是一个纯粹的数学对象。然而,编程是一种魔术。我们可以拿一个数学对象,把它描述成一种语言,看它能操纵物理世界。编程是连接这两个世界的独特学科。"


试着让你的学生编一个魔术8球。回答"是"或"否"的基本8号呼叫可能用少于10行的代码进行编程,并且可以以任何方式递增扩展:

  • 首先,使其简单化:在cli中输入类似于"s"的内容来震动;8所有答案都是"yes"或"no"。
  • 接下来,输入问题,显示问题和答案
  • 然后展开可能的答案……一大堆选择,那些很快就能抓住机会的学生可以得到一些乐趣("看,电脑说脏话!"!"),而你帮助其他人
  • 实施一个计时器,这样你就不能马上再问同样的问题,以防你不喜欢答案。
  • 将可能的答案分为"是"、"否"和"模糊"等变量;第一个RNG决定答案的类型,第二个RNG决定具体的答案。
  • 重新配置计时器;如果答案模糊,您可以立即再次询问
  • 在文本周围加一个*的框架
  • 等等…
  • magic 8球是大多数人都能联系到的东西,它是对基本字符串、float/ints、io、cli、boolean和rng的介绍,只使用最简单的工具。它很简单,(有点)有趣,并且可以很容易地扩展。根据您的方法,您可以使用类8ball()、类yesanswer()和whatnot立即使编程面向对象。

    祝你好运;


    如果你是教授工程师,这段序言可能会引起他们的注意:

    1
    2
    3
    4
    5
    6
    7
    8
    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).

    只要写下规则,你就有了一个程序,可以用8行代码完成第一学期的所有微积分。


    我认为这个问题真的是个好主意。我有很多差劲的老师,最棒的一个,很明显那些有意愿炫耀一点的人。

    有很多代码可以显示。我首先想到的是EdFelten的tinyp2p源代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
      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"))

    好吧,它比你的"十"限制多5行,但仍然是一个功能齐全的对等2应用,从thansk到python。

    tinyp2p可以作为服务器运行:

    1
    python tinyp2p.py password server hostname portnum [otherurl]

    和客户:

    1
    python tinyp2p.py password client serverurl pattern

    当然,讲故事很重要。为此,99瓶啤酒是一个很好的开端。

    然后,您可以选择几个有趣的代码示例,如:

    • 著名的Python一号班轮:

      print("".join(map(lambda x: x and"%s%d bottle%s of beer on the wall, %d bottle%s of beer...
      Take one down, pass it around.
      "%(x<99 and"%d bottles of beer on the wall. "%x or" ", x, x>1 and"s" or"", x, x>1 and"s" or"";) or"No bottles of beer on the wall.

      No more bottles of beer...
      Go to the store and buy some more...
      99 bottles of beer.", range(99,-1,-1))))

    • 欺骗的python版本(对学生来说很酷,因为它显示了网络特性):

      import re, urllib
      print re.sub('

      ', '', re.sub('|

      |
      |
      ','
      ', re.sub('No', '
      No',
      urllib.URLopener().open('http://www.99-bottles-of-beer.net/lyrics.html').read()[3516:16297])))

    最后,我将遵循前面的建议并显示一些JavaScript,因为它非常直观。jquery ui演示网站有很多不错的小部件演示,包括代码片段。几行日历:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <script type="text/javascript">
        $(function() {
            $("#datepicker").datepicker();
        });
       



    <p>
    Date: <input id="datepicker" type="text">
    </p>

    书签也有很多性吸引力。可读性非常有趣:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    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);
    }


    我被一些在TalkEasyAI和python(视频和pdf)中显示的东西给吓坏了。例如,教一台计算机如何玩"主脑",解决八个皇后,字母游戏(这些难题类似于"9567+1085==10652",并推断数据中的关系)。全部按10行的顺序排列(可能有20或30行"幕后"代码)。


    斐波那契数是学习递归性的一个很酷的例子。它表明递归性可以很简单地编写,并且执行起来也很昂贵。后面可以介绍负条目案例。

    1
    2
    3
    4
    5
    6
    7
    8
    int fiboNumber(int index)
    {
      if (index <= 1)
      {
        return index;
      }
      return fiboNumber(index - 1) + fiboNumber(index - 2);
    }

    我记得发现简单的循环很神奇。每次我学习一门新语言时,我都会把这样的东西放在一起:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <?php
    $numberOfBottles = 99;
    print("$numberOfBottles Bottles of Beer on the Wall");
    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!");
    ?>

    也许一些与while或foreach循环的变化也很容易。


    你可以让你的学生去codeplex ironpython Silverlight示例站点,其中包括一个<10行的改变画布和与鼠标交互的演示。您可以在此处找到Silverlight示例

    仅仅看到在Web浏览器中编写的代码,然后对一个小的WPF进行修改,可能会让一些人陶醉。


    来自安德鲁·库克的《马尔博基:你好,世界》

    让他们在Malbolge试试这个:

    1
    (=<`$9]7<5YXz7wT.3,+O/o'K%$H"'~D|#z@b=`{^Lx8%$Xmrkpohm-kNi;gsedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543s+O<oLm

    这是全世界最困难的编程语言中的"hello world",花了两年时间才找到。

    他们可以去卢·谢弗的《Malbolge》一页。

    你当然可以去1号公路(!!!!)世界上99瓶啤酒计划由Hisashi Iizawa(这是一个单内衬!)这是酒井正彦在Malbolge上的pdf


    • 选择在屏幕上绘制点、线、框或圆的任何语言(或框架)。设计游戏是很多程序员第一次发现他们的热情的地方,图形输出是这一点的基础。
    • 选择一种能让他们轻松向朋友炫耀自己的工作的语言。如果他们需要让朋友安装运行时框架,并按照复杂的说明进行展示,那么他们就不会得到必要的荣誉和评论。不要低估同龄人说"嘿,太酷了!"的价值。

    也许考虑到这两个标准,带processing.js或flash的javascript可能是一个很好的起点,尽管flash显然有要求的缺点。呃。。。闪光灯。

    切切的想法:flash实际上是教OOP的一个非常好的方法,因为当你真正看到对象和类的概念时,它更容易掌握。


    我认为任何一种可以做一些有用的shell脚本都是向某人展示编程能力的好方法。在我看来,花10到20分钟的时间编写一个小脚本,可以自动完成另一项任务并为您节省无数小时,这是非常令人印象深刻的。

    例如,我曾经编写了一个简单的Perl脚本,将一个目录中的MP3文件转换为另一种格式,然后将它们烧录到CD上。你用MP3目录的路径调用脚本,它会烧录CD。至少当时我印象深刻。


    您可以使用jquery(少写,多做)库在HTML Web表单中以最少的编码实现出色的视觉效果。否则,像f这样的函数语言也可以用很少的代码行来做很多事情。以下是项目Euler问题8的解决方案:

    数据:50*20网格中的数字串

    让data=txt>seq.tolist>list.filter system.char.isdigit>list.map system.char.getNumericValue

    让rec分区_5 l=匹配L| x1::(x2::x3::x4::x5::u as t)->[x1;x2;x3;x4;x5]::(partition_5 t)[-]>

    让euler_8=list.map(fun x->list.fold(*)1.0 x)(分区_5数据)>list.max


    我一直喜欢河内塔。在方案中

    1
    2
    3
    4
    5
    6
    7
    8
    9
    (define (hanoi x from to spare)
      (if (= x 1)
        (begin
          (display"move")(display from)(display" to")(display to)(display"
    "))
      (begin
        (hanoi (- x 1) from spare to)
        (hanoi 1 from to spare)
        (hanoi (- x 1) spare to from))))

    实例输出

    1
    2
    3
    4
    5
    6
    7
    8
    9
    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>

    在python中也是如此(尽管不能像Scheme版本那样制作1000张光盘)

    1
    2
    3
    4
    5
    6
    7
    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)

    如何处理javascript?我不知道处理过程,但是代码对于它所能做的来说总是很小,它非常直观,您可以在浏览器中运行它。http://processingjs.org/展览


    使用游戏!不是编码游戏,而是编码比赛。想想谷歌人工智能的挑战,然后把它哑了。

    让我举个例子。我曾经和我的朋友们进行过一次小小的竞争:我们中的一个人建立了一个模拟框架,其余的人编写了一个从简单到严重的肛门的人工智能,我们发起了100次测试来看看哪个人工智能的表现最好。

    框架?基本I/O:模拟控制由一个进程执行,该进程为每个竞争的AI生成一个子进程,每一轮模拟将数据写入标准输入管道,并读取输出。这样,只要遵循一个非常简单的协议,我们就可以用我们想要的任何语言编写我们的人工智能。

    规则非常简单,但这件事很有挑战性:我们有两个村庄,A和B,它们将钱平均分配给住在那里的家庭。A有800枚硬币要给,B有500枚。每一轮,所有的人工智能被要求选择一个村庄居住(打印"A"或"B"到stdout),然后得到每个村庄在此期间的总数(通过读取stdin中的数字)。目标是在100回合后获得最多的钱。

    我们创建的一些人工智能有着非常复杂的机制来尝试和猜测定居在哪个村庄——尽管它们并不真正好,因为胜利者的策略总是选择上一轮给每个家庭最少钱的村庄(假设大多数人下次会搬到另一个村庄)。

    我认为这是一种积极的、鼓励研究的、健康的竞争方式。有成千上万的游戏可以玩,它只需要基本的编程知识(标准I/O!)让玩家互动。


    我用4行代码创建了高级计算器


    在http://www.youtube.com/watch?v=a9xakttwgp4你可以观看Conway用大约5行apl(一种编程语言)编程(同时口头评论)的生活游戏。

    观看节目很有趣,能启发学生编程很酷,数学,数学,简洁的编程语言:)

    顺便说一句,鲍勃·马丁叔叔在汉塞尔分钟的播客中提到了这段YouTube视频。


    我的第一个程序与这里已经提到的程序有些相似,但是我的程序短了一行,而且更礼貌:

    1
    2
    3
    10 PRINT"What is your name?"
    20 INPUT A$
    30 PRINT"Thanks"


    这是我的10线蜘蛛网。从技术上讲,它是11个,包括perl shell声明,但我希望这是可以原谅的!

    我想让它识别某些文件类型并支持相对路径,但是行数用完了!

    运行:

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

    请注意,谷歌不允许没有用户代理的LWP简单,因此搜索谷歌将无法工作。也没有空间!不管怎样,代码在哪里:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #!/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
    ";
        push(@queue, $html =~ m/(http:\/\/[^'"]*)/g);
    }

    吱吱声是激发灵感的好工具

    例如:http://squakland.jp/school/drive_a_car/html/drivecar12.html


    用python将图像转换为音乐

    从我的答案到如何使用python循环每4行中的每4个像素?:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #!/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

    音符可以对应不同的音调。这里我用的是等温标度:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    # 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()

    有点偏离主题,但您可以查看这个tweet编码,它使用的是少于140个字符的as3代码:

    http://gskinner.com/playpen/tweetcodeingu 0/

    ^ ^ ^


    曼德尔布罗特集可以以一种不太复杂的方式呈现,例如在下面的Java中:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    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);
        }
    }

    受到Robin Day和John Topley答案的启发,让他们将以下内容粘贴到浏览器的地址栏中:

    javascript:var name=prompt("你叫什么名字?","";var msg='hello'+name+"";newwindow=window.open();newdocument=newwindow.document;for(var i=0;i<100;i++)newdocument.write(msg);newdocument.close();

    或者更清晰地说:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    var name=prompt("What is your name?","");
    var msg='Hello '+name+'';
    newwindow=window.open();
    newdocument=newwindow.document;
    for (var i=0;i<100;i++)
    {
        newdocument.write(msg);
    }
    newdocument.close();

    我写这个是为了一个论坛游戏——在尽可能少的行中编写rot13算法。那么,用C语言写这个怎么样?

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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);
    }

    我认为三元运算符非常整洁,尽管我听说它比if构造慢。我还没来得及为自己计时…


    当我还是个孩子的时候,我对计算机(当时的MSX)有着浓厚的兴趣,因此编程(所有的东西,都是BASIC的变体)。我长大后就失去了这个功能,但当我得知反恐精英只是一些粉丝修改半衰期代码而制作的一个模型时,我又回到了它的身边。这让我再次对编程非常感兴趣!

    这不是10行代码,但是如果你给人们看一些游戏的源代码,然后修改它,让它做一些不同的事情,并向他们演示它的真实性,它真的会把它们吹走。哇,这其实不是黑暗魔法!你能行!

    现在,有一天,有很多游戏你可以做到这一点。我认为所有地震系列(至少是I到III)的源代码都已发布。我知道你可以为半衰期和半衰期创建mods 2,我相信其他游戏如虚幻和滑稽也提供类似的能力。

    一些简单的事情会激发你的动机:

    • 使武器超级强大(例如无限弹药、更高伤害、自动瞄准)。等。
    • 添加一个动画风格的动作(飞行,冲刺真的很快,等等)。

    修改本身不应该占用太多的代码行,但是它的工作原理是惊人的。


    有点像…

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    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

    首先,为了在最短的时间内获得最大的关注,您需要使用高级语言。也许你会想显示3D。

    我会使用OpenGL——我会先展示一个3D电脑游戏的简短场景,然后解释,这是通过将大程序分成小部分,然后向他们展示小部分的样子来完成的。比如nehe.gamedev.net上的第05课,或者更高级的课程。这很令人印象深刻,也不太复杂。

    另外,您可能还需要检查Alice,它包含3D并且是为教学而设计的。


    在WPF中,您可以在几个XAML行中编写一个功能完整的缩略图视图:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <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>

    这是假设您有一个MyItems集合,其中包含指向图像文件的FullPath属性。

    魔力来自将每个列表框项转换为图像的ItemTemplate,以及将默认垂直堆栈面板更改为包装面板的ItemsPanelTemplate


    大多数答案都使用某种类型的API,这打破了10行代码的要求。每个API调用可以是数百行代码。最初的问题是使用"简单代码"。对我来说这意味着没有API调用。我们能想出什么样的答案,仅仅使用"简单代码"的定义?


    Ruby/python/perl中的基本grep应用程序。


    10印"磨憨"20 GTO 10


    嗯,我记得我在Qbasic上做雪花和火的时候,一个朋友过来告诉我如何做一个旋转的三维立方体,我完全疯了。

    然后我把火改成立方体,这是个好时机。

    我得看看我能不能在某个地方找到那些旧剧本,它们不是很长。


    我认为在python中使用nodebox的一些很酷的过期元素将是一个很酷的开始。它具有从正方形到复杂路径的绘制功能。它甚至可以从mac isight/webcam中获取图像,并通过缩放、旋转和应用过滤器对其进行操作。

    不幸的是,它只适用于Mac OS X,所以我认为它不会有太大的用处,但作为一个例子(如果你自己有一台Mac),它可以用一点代码来实现,它会非常漂亮。


    递归也可以用来解迷宫。就像锡尔宾斯基三角和其他艺术一样,对我来说,这比解决一些数学问题有趣得多。


    使用javascript很有趣

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    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();

    只有10行!您可以将其包含在网页中,也可以将下面的代码复制粘贴到浏览器的URL栏中,然后按Enter键。

    1
    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();

    好玩吧?


    在您提供的SAPI示例的基础上,我使用它自己大声读取文件(只需将文本文件拖放到其图标上或从命令行运行它即可)。

    SpabFiel.VBS:

    1
    2
    3
    4
    5
    6
    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

    这是我见过的最酷的东西…当故障发生时,其实很简单:

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


    当我还是个孩子的时候,这是有史以来最酷的事情:

    1
    2
    10 PRINT"BEDWYR"
    20 GOTO 10

    我想这几天不会减少很多;)


    我相信从地震3开始,速度非常快1/sqrt(x):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    #include <stdio.h>
    #include <stdlib.h>
    int main (int argc, char const* argv[])
    {
        if (argc != 2) {
            printf("Need a number!
    ");
            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
    ", y);
        return 0;
    }


    到处乱吃饼干。

    饼干!孩子们吃饼干!

  • 找到一个依赖cookie的网站。
  • 使用firefox插件编辑cookie。
  • ?????
  • 学习!!!!