22
votes

I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}

60 characters exactly!

Thanks so much for your wisdom!

9
  • 22
    Why was brainfk censored? Can't we be adults and not tell everyone what they can and cannot read? In this context brainfk is not an obscenity. Nov 6, 2010 at 21:28
  • 2
    I suspect this question will be closed. Try improve it to be more constructive. See: blog.stackoverflow.com/2010/09/good-subjective-bad-subjective
    – Maniero
    Nov 6, 2010 at 23:41
  • 8
    @bigown: This is a good subjective one and is constructive. It's no different than asking for famous quotes. In fact, it's better, because it's asking for famous code/equation "quotes." :-)
    – Macneil
    Nov 7, 2010 at 0:30
  • @Macneil:I think the same, but the question is poor, it can be improved.
    – Maniero
    Nov 7, 2010 at 4:22
  • 3
    @bigown: honestly, I can't really see how this question could be any more constructive. Not to doubt you or so, but very genuily asked, could you suggest an improvement to @BeachRunnerJoe? I actually very much enjoyed the answers and learned a lot from them. I'd love to see this question reopen.
    – Joris Meys
    Nov 7, 2010 at 20:31

35 Answers 35

34
votes

The classic C string copy routine is known by fewer and fewer people theses days:

while (*d++ = *s++);
14
  • 3
    yes, very famous...to the veterans! Nov 6, 2010 at 19:27
  • 13
    While I understand it has "historical" value it's terrible terrible code, so the fact that it's falling in disuse is a good thing =) Nov 6, 2010 at 19:34
  • 9
    A C veteran would recognize the pattern immediately. It's idiomatic C. Nov 6, 2010 at 19:47
  • 6
    Always thought this was incredibly cool.
    – Maulrus
    Nov 7, 2010 at 1:00
  • 5
    I must say, I agree with @Kop. In just a few chars, it shows signifficant flaws of its standard lib and its semantics. One of the most absurd things is strings being 0-terminated instead of length-prefixed (which is safer and makes determining the length of a string O(1)). The second thing is that C doesn't have actual boolean values (which fixes the if (alarm = red) launchNukes();-trap). Dijkstra would consider this code more than harmful. I do agree it is imperative for a C programmer to at least understand this code, but I think it's more important for him to know how to do it better.
    – back2dos
    Nov 7, 2010 at 13:12
25
votes

not one line, but I present The World's Last C Bug:

    status = GetRadarInfo();
    if (status = 1)
      LaunchNukes();
3
  • 2
    That's one of those "Oh sh*t!" errors. Nov 11, 2010 at 1:49
  • 3
    it's LaunchNukes();
    – hasen
    Nov 12, 2010 at 21:24
  • 1
    if that has been written as: if(GetRadarInfo()=1){...}, we wouldn't get this bug because it doesn't compile. So don't always introduce intermediate variable.
    – tactoth
    Jan 27, 2011 at 2:45
22
votes

I see Conway's Game of Life in APL floating around a lot:

An extra bonus is that this will make sure you're handling unicode correctly.

7
  • 2
    ha! that's the first thing I thought of when I saw your code, nice! Nov 6, 2010 at 19:24
  • Wow, that's impressive!
    – FinnNk
    Nov 6, 2010 at 22:43
  • 4
    Explanation: youtube.com/watch?v=a9xAKttWgP4
    – jfs
    Nov 7, 2010 at 21:28
  • 15
    And I thought Perl looked like line noise. Nov 8, 2010 at 20:17
  • 1
    @Greg, just wait, APL uses more than the roman and greek alphabets because there weren't enough letters and symbols already; backspace (more properly called "overstrike") is also used because some characters need to be typed on top of other characters. One such was a divide symbol on top of a square, which represented matrix inversion (if unary operator, or multiplication by the inverted matrix if it was used as a binary operator).
    – Tangurena
    Nov 10, 2010 at 21:32
19
votes

A modified version of a famous Perl one-liner:

/^.?$|^(..+?)\1+$/

This regular expression matches strings whose length is prime.

The original version is:

/^1?$|^(11+?)\1+$/

which matches strings consisting of a prime number of 1s.

14
votes

Quicksort:

qsort []     = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)

If the list is empty, the sorted result is the empty list.

If the list starts with the element x, and the rest of the list is xs, then the sorted result is list consisting of the sorted list consisting of all elements in xs less than x concatenated with the element x concatenated with the sorted list of all elements in xs larger than x.

(or in other words - divide in two piles, all less than x and all larger than x, sort them both and create a list with the less-than pile, the element x, and the larger-than pile).

Beats the understandability of the C version quite easily.

6
  • 1
    This is Standard ML? Or Haskell? Nov 6, 2010 at 21:02
  • 3
    Haskell. I like the mindset of the language.
    – user1249
    Nov 7, 2010 at 1:00
  • I like the partitioning alternative qsort (x:xs) = qsort lesser ++ equal ++ qsort greater where (lesser,equal,greater) = part x xs ([],[x],[]) Nov 8, 2010 at 23:40
  • 1
    Is there a version of this that uses a random pivot instead of the head of the list? That would make it closer to C.A.R. Hoare's original.
    – Macneil
    Nov 11, 2010 at 2:07
  • 1
    Hoare says "The item chosen [as pivot element]... should always be that which occupies the highest-addressed locations of the segment which is to be partitioned. If it is feared that this will have a harmfully non-random result, a randomly chosen item should initially be placed in the highest-addressed locations". So to be true to Hoare, we should work with the last element, not the first.
    – user1249
    Nov 11, 2010 at 10:16
13
votes
  1. The Ackerman function. The implementation of the Ackermann-Péter version should fit into 60 chars :)

  2. This lovely hexadecimal constant: 0x5f3759df. It is the heart of the most WTFing code I've ever seen: the fast inverse square root.

  3. The famous XOR swap.

  4. question = /(bb|[^b]{2})/

2
  • 3
    +1 for inverse square root
    – Macneil
    Nov 6, 2010 at 23:40
  • @Macneil Argh! I was just thinking of that one.
    – Mark C
    Nov 7, 2010 at 4:02
13
votes

When I first figured out the bash forkbomb, I thought it was really sweet.

:(){ :|:& };:
2
  • Wow, that's just evil!
    – Macneil
    Nov 11, 2010 at 2:05
  • Look at all the smilies! You could call this "The Smiley bomb!"
    – Mark C
    Nov 11, 2010 at 16:28
11
votes
print "hello world\n";

and its derivations seems to be popular. :-)

1
  • 1
    +1: easily the most 'famous' - deserving or not. Dec 5, 2010 at 8:44
10
votes

Because you mention equations, this one belongs on your list:

e^{i\pi}+1=0

(Wolfram Alpha rendering: e i pi + 1 = 0)

3
  • Yes it does! Good ol' Euler, another good one! Nov 6, 2010 at 19:30
  • I remember this as e^{i/pi} = i^2
    – Josh K
    Nov 8, 2010 at 23:44
  • @Josh K: That's because i² == -1, so you can balance the equation by subtracting one from both sides, removing the +1 and changing the =0 to -1 or
    – Daenyth
    Nov 9, 2010 at 1:08
7
votes

How to detect even numbers:

x % 2 == 0
3
  • 3
    Or !(x%2) in sane languages. Nov 7, 2010 at 4:11
  • 8
    Or !(x & 1) in languages without optimizing compiler.
    – jfs
    Nov 7, 2010 at 21:34
  • 1
    @Christian, numbers should not be booleans - too easy to make a mistake.
    – user1249
    Dec 3, 2010 at 10:37
7
votes

import this in Python.


EDIT as comments cannot contain line breaks: For those without a Python interpreter handy, this is the output

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
4
  • I'm a Python beginner. What would this achieve?
    – Richard
    Nov 12, 2010 at 21:13
  • 1
    @Richard: Try writing this in the Python interactive interpreter :).
    – MAK
    Nov 13, 2010 at 5:52
  • This brightened up my Sunday afternoon :)
    – Richard
    Nov 14, 2010 at 12:39
  • @Richard Serious question: If you run this, does it give you a stack overflow?
    – Mark C
    Nov 19, 2010 at 1:19
6
votes

Not quite 2 lines but I would say this is quite famous:

void swap(float* x, float* y)
{
    float t;
    t = *x;
    *x = *y;
    *y = t;
}

Actually some languages can describe it in one line. Lua comes to mind but there are more.

x, y = y, x
13
  • definitely famous! Nov 6, 2010 at 19:17
  • 7
    with ints: a ^= b ^= a ^= b;
    – JulioC
    Nov 6, 2010 at 21:44
  • I'm just curious how is this implemented? does it create a temporary table (y, x), then assign x the 1st element and y the 2nd element?
    – tactoth
    Nov 8, 2010 at 7:58
  • Also I'm wondering how often do people swap values in real life programing.
    – tactoth
    Nov 8, 2010 at 7:58
  • 1
    @tactoth - Swapping is commonly used for implementing strongly exception safe assignment in C++.
    – Kaz Dragon
    Nov 8, 2010 at 9:30
6
votes

My favorite lambda calculus example is the Y combinator:

Y = λf.(λx.f (x x)) (λx.f (x x))
6
votes

From an exercise in K&R, here is a function that will return how many bits are set in the number given. At 58 characters:

int bits(int n){int b=0;while(n){n=n&(n-1);b++;}return b;}

It takes time proportional to the number of bits set. The "ah ha" part here is that

n = n & (n - 1)

Removes the rightmost set bit from n.

1
  • Awesome, nice K&R reference! Nov 6, 2010 at 19:59
6
votes

Recursive Pascal's Triangle in One Line (Haskell)

  r n=take(n+1)$iterate(\a->zipWith(+)(0:a)$a++[0])[1]

Fifty-two characters, add spaces to taste. Courtesy of "Ephemient" in the comment here.

I thought this was a better example than the cryptic but brief solutions in J and K (though I'm no Haskell user, yet).

6
votes

Unix Roulette (DANGER!)

Courtesy of Bigown's answer in the joke thread (and the comment):

[ $[ $RANDOM % 6 ] == 0 ] && rm -rf /* || echo Click #Roulette

(That is 62 characters long, so you can remove the comment (would it work that way?) or some non-essential spaces.)

2
  • 2
    Please mark this as dangerous. Dec 3, 2010 at 11:34
  • I use zsh and it doesn't work unless s/==/-eq/ :-)
    – defhlt
    Aug 7, 2012 at 9:27
5
votes

Infinite Fibonacci Sequence (Haskell)

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
1
  • Why not fibs = 0 : scanl (+) 0 fibs?
    – FUZxxl
    Nov 27, 2011 at 22:18
4
votes
DO 10 I=1.3

This is one of the most expensive bugs in history. This Fortran statement assigns the float value of 1.3 to the variable named DO10I.

The correct code - the header of the loop repeating statements until the statement labeled 10 and the loop variable I accepting values 1, 2, 3:

DO 10 I=1,3
2
  • 1
    Why is it an expensive bug? Nov 10, 2010 at 21:06
  • 2
    This bug was in a subroutine that calculated orbital trajectories for a 1961 Mercury space flight. However, it was caught and fixed before launch, and was therefore not a costly bug. There was a similar bug on a Mariner mission that did cause failure of the mission, though. (source: Expert C Programming, pages 31-32.)
    – Darel
    Nov 22, 2010 at 20:23
4
votes

Duff's Device:

void send(short *to, short *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);
    }
}

Tom Duff unrolled a memory-mapped port write into one of the most bizarre C constructs the world has seen.

1
  • It doesn't fit into 60 characters, but it def is cool. I remember getting chills seeing his name scroll past in the credits to some Pixar movie.
    – Macneil
    Nov 12, 2010 at 4:48
2
votes
val (minors, adults) = people.partition(_.age < 18)

The above line of Scala code partitions people (a list of Persons) into two lists based on their respective ages.

It takes the following much of code to do the same thing in Java:

List<Person> minors = new ArrayList<Person>();
List<Person> adults = new ArrayList<Person>();
for(Person p : people) {
  if(p.age < 18) {
    minors.add(p);
  } else {
    adults.add(p);
  }
}
2
votes

Swapping the values of two variables without using a third variable. This is one of the first things in programming that I was told and thought "Hmm... that's cool"

int a,b; 
b=a-b;
a=a-b;
b=a+b;
2
  • I know you can do this using XORs, but this was my bit of nostalgia for today :)
    – Jonathon
    Dec 3, 2010 at 10:51
  • XOR has no problem with overflow. Does this?
    – Job
    Sep 3, 2011 at 21:04
2
votes

Black magic from John Carmack

float Q_rsqrt( float number )
{
    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
//  y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed

    return y;
}
2
votes

The largest number that can be represented by 8 Byte (Python)

print '\n'.join("%i Byte = %i Bit = largest number: %i" % (j, j*8, 256**j-1) for j in (1 << i for i in xrange(8)))
1
vote

Anything to do with Hello World comes to mind. You could go with different variations if you plan on storing multiple languages.

For something more non-trivial, there's Fibbonacci.

3
  • 1
    Fibbonacci, nice one! Here's the code... if (k < 2) return k;else return fib(k-1) + fib(k-2); Nov 6, 2010 at 19:23
  • 1
    @BeachRunnerJoe: You might want to combine that with the conditional operator ;)
    – back2dos
    Nov 6, 2010 at 19:41
  • 3
    yes indeed! return (k < 2) ? k : fib(k-1) + fib(k-2); Nov 6, 2010 at 19:45
1
vote
  1. Conditional operator :

    minVal = (a < b) ? a : b;

  2. Switch case

  3. for-each loop [Java]

8
  • 1
    Actually, conditional operator is the correct name. An operator is ternary if it takes three arguments.
    – back2dos
    Nov 6, 2010 at 19:46
  • @back2dos - Indeed, both C# and JavaScript call this the conditional operator. Nov 6, 2010 at 19:49
  • @back2dos - The ?: operator does take three arguments, which is why it is called the ternary operator. This has been the correct terminology from C onwards. (apparently starting from BCPL, according to Wikipedia...)
    – grkvlt
    Nov 8, 2010 at 23:08
  • @grkvlt: I never said it doesn't take three arguments. It's just that you wouldn't call ! the unary operator or + the binary operator. It's simply not exact.
    – back2dos
    Nov 8, 2010 at 23:25
  • 1
    @back2dos - I think this is our problem - I would refer to the apple as "the fruit" in that situation, but I think we're arguing grammar, not programming language syntax, and you are correct that ?: is the conditional operator ;)
    – grkvlt
    Nov 20, 2010 at 20:29
1
vote

This Quine from the Jargon File in C:

char*f="char*f=%c%s%c;main(){printf(f,34,f,34,10);}%c";main(){printf(f,34,f,34,10);}

There is also a LISP version there, too, but you can find many others floating around, in pretty much any language you could imaging...

1
vote

euler's identity which links the most beautiful numbers in math universe: 1, 0, e, i and π : e^i(π) + 1 = 0

1
vote

I had a good one and I wrote it down in the margin.

1
  • 2
    Nice one Fermat
    – Richard
    Nov 12, 2010 at 21:15
1
vote
int gcd(int a, int b)
{
   while(b>0)
   {
      int t = a%b;
      a=b;
      b=t;
   }
   return a;
}

Probably not famous, but one of my favorites. To most it's not immediately apparent why it works.

1
vote

This is a bit over 60 characters but it really depends on variable naming (so I'm including it!)

let readLines (rdr : StreamReader) =
      seq { while not rdr.EndOfStream do
                yield rdr.ReadLine()}

Nice little function to read a file into a sequence line by line in F#.

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