views:

2389

answers:

27

My favorite is Tom "Duff's Device". It took me literally months after I first found this before I felt like I fully understood it. That said, I have seen others (there is an amazingly short implementation of a regular expression engine by Brian Kernighan in the book Beautiful Code).

dsend(to, from, count)
char *to, *from;
int count;
{
    int n = (count + 7) / 8;
    switch (count % 8) {
    case 0: do { *to = *from++;
    case 7:      *to = *from++;
    case 6:      *to = *from++;
    case 5:      *to = *from++;
    case 4:      *to = *from++;
    case 3:      *to = *from++;
    case 2:      *to = *from++;
    case 1:      *to = *from++;
               } while (--n > 0);
    }
}

What is the cleverest code you've ever seen?

+6  A: 

Scott Hanselman has already done the work for you in his Source Code series

Mark Glorie
Good call - I love that series.
Erik Forbes
+2  A: 

Studying the strategy pattern in the Head First Design Patterns book was a moment i thought wow! It's something i would of never thought of, even approaching a problem like that i wouldn't of thought of let alone code.

Gary Willoughby
That book is amazing. Its the book that really learned me Design Patterns in a way that was fun enough to i can remember it.The remote and the gum ball machine always reminds me of thoose patterns (I forgot the patterns names :))
Jesper Blad Jensen aka. Deldy
+8  A: 
float InvSqrt (float x){
    float xhalf = 0.5f*x;
    int i = *(int*)&x;
    i = 0x5f3759df - (i>>1);
    x = *(float*)&i;
    x = x*(1.5f - xhalf*x*x);
    return x;
}
Martin
That's a classic :)
Rich
http://www.beyond3d.com/content/articles/8/
Gary Willoughby
was reading that just yesterday, interesting story.
leppie
+1  A: 

I think you'd have to follow whatever Mark Jason Dominus does in his Universe of Discourse, where he covers quite a few languages. He has been doing mathematical stuff lately (like, why most baseball players are under-average), but he can come up with very clever things in many languages. I knew him from the Perl world where he blows people's minds with his book Higher-Order Perl (referring to higher order functional programming).

That doesn't really answer your question because he does stuff I could never even dream of coming up with on my own. :)

brian d foy
+2  A: 

I wrote an Error Code architecture that is incredibly easy to use across the org, and has stood the test of time.

Simply, you define errors like this:

[ValidationError] [ErrorEntity("ThisThing")]
public class MyErrors : ErrorCollection
{
  static MyErrors() { Initialize(typeof(MyErrors)); }
  [ErrorField("Id")]
  public static readonly Error OMGTheDatabaseDidntLikeThatId;
  [ErrorField("Name")]
  public static readonly Error WhyDidYouUseThatName;
  [SystemError]
  public static readonly Error DatabaseNotFound;
}

There is a good chunk of crazy reflection stuff going on in the Initialize function (about 3 or 4 dozens lines of code), but it makes the syntax for defining and "throwing" this error really simple.

Initialize instantiates the Error objects with an error code based on the name of the field, and Entity, Field and Severity values based on attribution. The crazy part is that the Error class is a struct, so you can add more things to it at runtime (like an index, or a message) without affecting the "library" of error codes.

So, when you create an error (using an Error List class), you call code that looks like this:

Error.AddError(
  MyErrors.WhyDidYouUseThatName,
  1, // index
  "this sucks" // message
  );

This adds an Error object (yeah, the same type as stored in the ErrorCollection) with extra, runtime information, into a runtime collection to be returned to the caller.

I'm pretty proud of this design and the code behind it. It's been the standard for about a year now. It was even extended to incorporate some really neat database interaction with very little changes to the base code about 6 months later, without fundamentally changing the initial implementation.

Amazing code, to me, is code that implements a solid design which withstands the open-closed principle. It doesn't fundamentally change when it can take on new needs.

askheaves
+13  A: 

When I saw it, it opened my eyes and my life was changed forever.

10 PRINT "HELLO WORLD"
20 GOTO 10

Sure, it may be laughable now, but it was the harbinger of a profound change in the way I think.

garrow
And after this deep revelation, quickly I pressed "RunStop" and checked if it worked again... It worked, amazing! :)
Myrrdyn
10 PRINT "WAITING FOR"20 GODOT 10
VVS
+6  A: 

Another classic:

strcpy(to, from, count)
char *to, *from;
int count;
{
    int n = (count + 7) / 8;
    switch (count % 8) {
      case 0: do { *to = *from++;
      case 7:      *to = *from++;
      case 6:      *to = *from++;
      case 5:      *to = *from++;
      case 4:      *to = *from++;
      case 3:      *to = *from++;
      case 2:      *to = *from++;
      case 1:      *to = *from++;
    } while (--n > 0);
  }
}

Source: http://en.wikipedia.org/wiki/Duff's_device

Gamecat
Shouldn't this be strncpy? But at any rate, just wow... If it compiles, that's a fascinating construct. I wouldn't have thought it would, but I suppose it depends on how smart and/or literal the compiler is...
Matthew Scharley
Ah, Duff's device... loop unrolling done by hand
Myrrdyn
+1  A: 

The Total Fit algorithm for hyphenation and line breaking as devised by Knuth and Plass and used in TeX is stunning. More than anything, it showed me the power and beauty of graphs.

Here's an in depth explanation of how it works.

Hank
+3  A: 

Hello world in the first language i learned was the most amazing code. It was the code that amazed me the most because it worked!

I was so cool, i made my first program! :)

Jesper Blad Jensen aka. Deldy
+1  A: 

Ok, not code but story: the story (or history?) of Mel, a Real Programmer:

prose and original verses, via Jargon File...

Gosh, thinking this is real... staggering

Myrrdyn
+3  A: 

The International Obfuscated C Code Contest has some really amazing stuff you can do with to C.

David Schmitt
+2  A: 

I stepped through the mplayer code once and found this:

!!i != !!(i & FLAG)

(not exactly the same code - but literally)

It took me a while to undstand what this really does.

unexist
Why is it amazing? It's just hurting my brain.
VVS
It's just a nice Xor. ;)
unexist
Myrrdyn
The !! is an idiom to normalize values to 0 or 1. I'm not sure why it would be useful there since we only get to see the one line of code.
brian d foy
+21  A: 

I've not seen this, but as urban legends go, it might be true:

The Story of Mel

"There was a program to do that job, an "optimizing assembler", but Mel refused to use it.

"You never know where it's going to put things", he explained"

Lord knows what he'd think of today's 'point and click' approaches to coding :)

gbjbaanb
To a point that's true. I've seen a lot of programmers get caught up on problems because they have no idea what's going on behind the scenes. Layers and layers of abstraction have gotten many people to a point where they have no idea how things work.
Kibbee
good to read that again :)
SoloBold
It seems Mel was a real person: http://en.wikipedia.org/wiki/Mel_Kaye http://wps.com/projects/LGP-21/mel-the-programmer.html (which means the story could be true, or at least based on a true event).
CesarB
+1  A: 

I always thought the "Just another Perl hacker," stuff was pretty clever, although it's kind of the opposite of "beautifully clean" code. There's some kind of beauty in it, in my opinion, a very twisted beauty.

SoloBold
Just Some Guy
If by beauty, you mean really ugly, yes. Just kidding.
MrBoJangles
+11  A: 

I do not think your example code is clever at all, as it is ridiculously difficult to work out what it does.

Clever code must meet all of these requirements:

  1. Be easy to understand
  2. Work
  3. Achieve something in an elegant and succinct way

If it isn't easy to understand, then it is isn't clever code.

(Edited to remove the claim that hard to understand code is stupid code as there are occasions when it is necessary to write hard to understand code. Of course, it should then have copious amounts of documentation to explain it...)

David Arno
That's kind of a backwards idea... readability isn't always the highest goal of coding (think embedded systems). Sure a compiler can do a lot of optimizations for you, but that doesn't mean thinking of how to write optimized code is "stupid."
SoloBold
No. That is not "clever" code.
Paul Nathan
Readability should always be the highest goal of coding. Others will have to maintain your code after you have left and they will need to understand it
David Arno
That is patently ridiculous. I mean no offense, but everything isn't pretty app development in an IDE for a system with gigs of RAM and HD space. #1 goal of code is to work, #2 goal is to work fast. Sometimes you need hard to read code to do that. Readability while important is probably around #5.
SoloBold
I do not disagree that hard to read code is a necessity on occasions. Just do not call it clever code.
David Arno
epic fail for saying duff's device is not clever. Your programmer badge should be revoked.
Paolo Bergantino
It's clever, but not intelligent
harriyott
This code is indeed hard to understand by itself, but you're not considering it actually solved a problem under very rigid constrains(i.e. you're dismissing the context in which that 'device' was discovered). It made some computations *possible*, so I'd call it clever, even if it looks ugly.
Juan Pablo Califano
You're mistaking the point of clever code. Clever code solves a specific problem in a highly unorthodox way in what amounts to minimal resources. It's a novelty most of the time and a testament to the originator's resourcefulness.
Paul Nathan
@Vlion, I'm not mistaking it at all. I'm simply saying "clever" is completely the wrong word to use.
David Arno
I totally disagree. You have a warped sense of the definition of the word "clever". A clever solution is a non obvious solution, but there is no implicit level readability implied. Duff's Device is wickedly clever, and solves a real problem, elegantly.
dicroce
@dicroce. You are talking nonsense. A clever solution is one that is blinding obvious, once it is revealed. Duff's Device only appears clever to those easily duped into thinking impenetrable = clever. The day you work for a moron manager who hides his stupidity behind big words, you'll understand.
David Arno
I can find no online definition of "clever" that includes either readability or "blinding obvious". So I think David has just invented his own definition :-)
RoadWarrior
@RoadWarrior, who cares whether the definition is mine or not. The majority here agree that my definition is the right one after all :P And and clever solution is only blindingly obvious AFTER being revealed. Please keep up.
David Arno
+7  A: 

Wasn't there a small demo flight simulator application circling the newsgroups a couple decades ago where the code was in the shape of an airplane or something? I just looked for it online and can't seem to find it. Maybe my memory is bad.

edit: Josh helped me find it. Thanks, Josh.

http://www1.us.ioccc.org/years.html#1998
(it's the first entry labeled "banks")

1998 - 14th International Obfuscated C Code Contest

Best of Show:
Carl Banks
Penn State Department of Aerospace Engineering
232 Hammond Building
University Park, PA 16802 USA

http://www.personal.psu.edu/users/c/w/cwb129/

What can we say? It's a flight sim done in 1536 bytes of real code. This one is a real marvel. When people say the size limits are too tight, well, we can just point them at this one. This program really pushes the envelope! [...] you will need an X-ish system, and a select() system call.

#include            <math.h>
#include          <sys/time.h>
#include          <X11/Xlib.h>
#include         <X11/keysym.h>
          double L ,o ,P
         ,_=dt,T,Z,D=1,d,
         s[999],E,h= 8,I,
         J,K,w[999],M,m,O
        ,n[999],j=33e-3,i=
        1E3,r,t, u,v ,W,S=
        74.5,l=221,X=7.26,
        a,B,A=32.2,c, F,H;
        int N,q, C, y,p,U;
              Window z; char f[52]
           ; GC k; main(){ Display*e=
 XOpenDisplay( 0); z=RootWindow(e,0); for (XSetForeground(e,k=XCreateGC (e,z,0,0),BlackPixel(e,0))
; scanf("%lf%lf%lf",y +n,w+y, y+s)+1; y ++); XSelectInput(e,z= XCreateSimpleWindow(e,z,0,0,400,400,
0,0,WhitePixel(e,0) ),KeyPressMask); for(XMapWindow(e,z); ; T=sin(O)){ struct timeval G={ 0,dt*1e6}
; K= cos(j); N=1e4; M+= H*_; Z=D*K; F+=_*P; r=E*K; W=cos( O); m=K*W; H=K*T; O+=D*_*F/ K+d/K*E*_; B=
sin(j); a=B*T*D-E*W; XClearWindow(e,z); t=T*E+ D*B*W; j+=d*_*D-_*F*E; P=W*E*B-T*D; for (o+=(I=D*W+E
*T*B,E*d/K *B+v+B/K*F*D)*_; p<y; ){ T=p[s]+i; E=c-p[w]; D=n[p]-L; K=D*m-B*T-H*E; if(p [n]+w[ p]+p[s
]== 0|K <fabs(W=T*r-I*E +D*P) |fabs(D=t *D+Z *T-a *E)> K)N=1e4; else{ q=W/K *4E2+2e2; C= 2E2+4e2/ K
 *D; N-1E4&& XDrawLine(e ,z,k,N ,U,q,C); N=q; U=C; } ++p; } L+=_* (X*t +P*M+m*l); T=X*X+ l*l+M *M;
  XDrawString(e,z,k ,20,380,f,17); D=v/l*15; i+=(B *l-M*r -X*Z)*_; for(; XPending(e); u *=CS!=N){
          XEvent z; XNextEvent(e ,&z);
                               ++*((N=XLookupKeysym
         (&z.xkey,0))-IT?
         N-LT? UP-N?& E:&
         J:& u: &h); --*(
         DN -N? N-DT ?N==
         RT?&u: & W:&h:&J
          ); } m=15*F/l;
          c+=(I=M/ l,l*H
          +I*M+a*X)*_; H
          =A*r+v*X-F*l+(
          E=.1+X*4.9/l,t
          =T*m/32-I*T/24
           )/S; K=F*M+(
           h* 1e4/l-(T+
           E*5*T*E)/3e2
           )/S-X*d-B*A;
           a=2.63 /l*d;
           X+=( d*l-T/S
            *(.19*E +a
            *.64+J/1e3
            )-M* v +A*
            Z)*_; l +=
                                    K *_; W=d;
            sprintf(f,
            "%5d  %3d"
            "%7d",p =l
           /1.7,(C=9E3+
            O*57.3)%0550,(int)i); d+=T*(.45-14/l*
           X-a*130-J* .14)*_/125e2+F*_*v; P=(T*(47
           *I-m* 52+E*94 *D-t*.38+u*.21*E) /1e2+W*
           179*v)/2312; select(p=0,0,0,0,&G); v-=(
            W*F-T*(.63*m-I*.086+m*E*19-D*25-.11*u
             )/107e2)*_; D=cos(o); E=sin(o); } }
Kurt W. Leucht
Check the Obfuscated C Competition
Josh
+10  A: 

MapReduce.

Whilst it may not be the easiest thing to understand to start with, once you understand it, and how it works, it is incredibly elegant, and powerful.

jamesh
I had a go at it once, but the document I was reading from was, well, boring (I forget where I got it but I think it was a pdf from Google... yeah, very precice). Anyways, do you know of a good document explaining how it works?
Shawn
+10  A: 

Chaining. Very simple, but very effective. I saw it first in a grid control in the 1990s. The property-setting functions returned a pointer to the class instance so the properties could be set in one statement:

gridCell.SetFontSize(12).SetColour(0).SetBold(true);

etc.

Actually, this probably isn't the cleverest thing I've seen, but I like its elegance.

harriyott
Yeah, I'm all about bending the computer to the human's will not the other way around.
MrBoJangles
I'm also a big fan of object initialization, which is like your example above but, IMO, better: new gridCell{ fontsize = 1, someOtherAttribute=0, etc = 3}
MrBoJangles
true, as a = b = c = 0; is good, cout << "hello " << x << " world"; is brilliant.
gbjbaanb
There is no value to chaining like this except to confuse some poor maintenance programmer.
John Dibling
If that line of code confuses them, no wonder they are poor.
harriyott
+4  A: 

Check any of the Golf challenges, or the obfuscated code contests.

Personally, while 'clever' may work, I prefer "clear". (Though I've been known to write some pretty clever code on occasion).

warren
+2  A: 

pico is fairly astounding for what it does so compactly.

plinth
+1  A: 

I've seen a bit of C code that when compiled outputs its source code.

There's also one that outputs code, you can then compile it with itself to produce another program.

I bet someone can find which one it was...

widgisoft
Those are called quines if anyones looking for them.
Rich Bradshaw
+28  A: 

Just remember...

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -Brian Kernighan

Instantsoup
Writing "clever" code would be clear and easy to understand. Debugging wouldn't be a problem.
The Pixel Developer
+2  A: 

This is an old entry to the obfuscated code contest. It translates input from English to Tolkien's Elvish.

And the code is formatted in the shape of an Elvish rune. It may not be readable, but it's pretty clever.

faircloc
+10  A: 

While I don't think that your example is at all clever, it's pretty much just confusing, I would have to say that John Carmack's inverse square root calculation is pretty clever.

Kibbee
Umm... that actually wasn't Carmack's idea.
Cleaver would be apt.
MrBoJangles
I wouldn't call your example clever programming, either, however. Clever math more like it. http://www.beyond3d.com/content/articles/8/ - really, the magic is the constant, and not particularly the float->int->float recasting which makes it work.
David Titarenco
+2  A: 

There was a game once called Snipes that shipped with Novell that used the IBM symbol characters to draw a maze. See http://en.wikipedia.org/wiki/Snipes

In it there was a long sequence of the following:

LODSB
STOSW
LODSB
STOSW

There were 80 interspersed LODSB/STOSW instructions listed with no other instructions in between.

LODSB means load string byte, and is the same as:

char aRegisterLowByte;
char *sourcePtr;
*sourcePtr++ = aRegisterLowByte; // move [si] -> al

STOSW means store string word, and is the same as:

short aRegister;
short *destinationPtr;
*destinationPtr++ = aRegister;  // move ax -> [di]

The destination was the screen memory, and the screen memory was layed out with alternate attribute and character display bytes.

The above code was part of a draw string routine. The routine filled the AH register with an attribute byte. Then the number of bytes in the string was used to calculate where to jump to in the interspersed instructions. For example, if 30 characters needed to be displayed, then the jump would be after 50 of the interspersed instructions.

So this routine used loop unrolling to optimize the drawing of strings.

A: 

Not a code, but a shell command :(){ :|:& };:

it is called a fork bomb... simple one liner that will halt system if not configured properly

technomage