Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Douglas Adams was born on March 11, 1952, and died when he was just 49. In honor of this wonderful writer, I challenge you to display 42 in the most creative way possible. Now this can be printed in the log, using some convoluted way of getting to 42, displayed in ASCII, just to name a couple of ways. Because this a popularity-contest, whichever answer has the most upvotes by March 11, will be declared the winner.

Note: this is not a duplicate. The question it was marked as duplicating was a code-trolling question whose goal was to write code to output 42, not find the most creative way to display it.

Winner: grovesNL! With an astounding 705 votes! Congrats!

Honorable Mentions:

Mr Lister C 228 For the clever use of #define

David Carraher Mathematica 45 For the complicated and convoluted math function to achieve 42

Aschratt Windows Calculator 20 Because, well, it's windows calculator And definitely 1337.

f.rodrigues Python 17 Because of the clever use of using external programs. And MSPaint

Jason C LMGTFY 14 For the use of LMGTFY (Let Me Google That For You)

Trimsty Python 12 For the clever use of an error message to output 42.

Mukul Kumar C++ 7 For the nice ASCII output.

If you think that there is another answer worth putting on the list, please comment it!

share|improve this question
5  
The old closed question was a code-trolling, i.e, anything that does not shows 42 beside appearing to do so or do it in a really horrible way. This one is not code-trolling, i.e. the output should really be 42 in a nice way. Hence it is not duplicate. –  Victor Feb 23 at 22:59
2  
@DanDascalescu This SE site has many questions without strict requirements, which allows users to exercise creative freedom in their answers. Sometimes too many restrictions can impede the expression of creativity –  grovesNL Feb 24 at 0:45
9  
The question should remain at 42 votes. –  Sampriti Panda Feb 24 at 3:47
23  
Marvin The Robot "I would post my brilliant answer, but you would probably down vote it. Being right all the time is so depressing." –  Mathew Foscarini Feb 24 at 16:43
3  
Can we get 42 favorites? –  Milo Feb 24 at 22:48

100 Answers 100

up vote 735 down vote accepted

Double Brainfuck

           +++++[>++[>+>+        ++>++++>++++>++++>++++++
          >++++++>+++++++        ++>+++++++++<<<<<<<<<-]>>
         >+>+>+> >>>+[<]<        -]>>       >++>-->>+>>++>+
        >--<<<<  <<<.....         .>            ....<......
       ...>...   <<.>....                       >.>>>>>.<.
       <<<<..     ..<....                      >..>>>>>.<
      .<<<<.      >>>.<<.                     >>>>>.<.<
      <<<<<       <.>...>                    >>>.>>>.
     <<<.<        <<<..>>                  .>>>>>.<
    <.<<<         <<...>>                 >>>.<<<
   <..<.          ...>...               <<.>..>.
   >>.<.<<...>>...<<...>>...<         <....>>..
  .<<<.>.>>..>.<<.......<....        .....>...
                 <<.>...            .....>...
                 <......           .>>>.<<..
                 <<.>...          .....>...<......>.>>.<.<<<
                 .>......        ..>>...<<....>>.....>.<..>.

which outputs...

      ++++         +++
    +[>++++    ++[>+<-][
   <]<  -]>   >++    +++
  +.-   ---   ---    ---
 --.+++++++         +++
        +++       .++
        +++      +.-
        ---    -----.--.

which outputs...

6*7=42
share|improve this answer
70  
I always thought something was fundamentally wrong with the universe. –  mfitzp Feb 23 at 14:05
125  
It should be 6*9=42. –  Proxy Feb 23 at 18:14
14  
@Proxy: True, but sometimes those references are lost on the viewers, even despite the context... ;-) –  grovesNL Feb 23 at 20:30
11  
@IsmaelMiguel: That's so base 10 of you... –  Dennis Feb 23 at 23:57
19  
I upvoted the whole question just so people would see this answer. –  Michael Stern Feb 24 at 0:52

C

Here's an oldie but goodie...

#include <stdio.h>

#define six  1+5
#define nine 8+1

int main()
{
    printf("what do you get when you multiply six by nine?\n");
    printf("%i x %i = %i\n", six, nine, six*nine);
}

This program contains 42 different ASCII characters.

share|improve this answer
14  
that is awesome –  ASKASK Feb 23 at 17:55
34  
I love the use of #define to get the math "right" ^^. You're a hoopy frood. –  Olivier Dulac Feb 24 at 9:51
31  
@mikhailcazi: The preprocessor will replace those constants literally, so six*nine becomes 1+5*8+1 which is 42. Well done Mr Lister. –  canaaerus Feb 24 at 11:41
6  
@canaaerus Holy shit, that is genius. Bravo, Mr Lister! –  mikhailcazi Feb 24 at 12:22
3  
@mikhailcazi #define works in C++ exactly the same way as in C. –  Mr Lister Feb 24 at 16:50

Brainfuck

Took a while to get there, but I like the result:

         +++++          +++[>+>++>
        +++>++        ++>+++++>+++++
       +>+++++       ++>+        ++++
      +++ >+++       ++++        ++>+
     +++  ++++                   ++>+
    +++   ++++                  +++>
   +++    ++++                 ++++
  +>+     ++++               ++++
 +++      +>++             ++++
++++++++>+++++++++       ++++
++>+++++++++++++++     +<<<
          <<<<        <<<<
          <<<<       <-]>
          >>>>       >>----.++++<<<<<
          <<>>       >>>>++.--<<<<<<.

When run, it will print 42, of course.

share|improve this answer
5  
Not even going to try (to beat or understand)... That does remind me of a lot of entries I've seen for the International Obfuscated C Code Contest. –  impinball Feb 23 at 6:42
51  
I have to admit, the font styling of the code to show "42" is gorgeous... –  WallyWest Feb 23 at 6:56
10  
I wish they wrote the Linux kernel in brainfuck. –  devnull Feb 23 at 7:12
8  
Sadly, you've been outdone by grovesNL. –  Blacklight Shining Feb 23 at 13:58
6  
I agree. Their font doesn't look as nice as mine, but the nested output is a really cool idea. Also their code makes more sense than mine. I first designed the font as ascii art and then played around with the code to make it fit the 220 character count of the ascii art, so my code contains much pointless stuff. –  Donarsson Feb 23 at 14:05

JavaScript:

var ________ = 0.023809523809523808, ____ = 1, ___ = 0, __ = 0, _ = 1;

       __ -           ___
     /_  |0        //     \\
    /_/   0     //          \\
   /_/_  |0                //
  /_/_   |0              //
 /_/____ |_           //
/________|0        //
         |0     //______________

The output is:

42

Not bad, eh? :)

For the people who don't understand, it actually evaluates the following:

__ - ___ / _ | 0 / _ / 0 / _ / _ | 0 / _ / _ | 0 / _ / ____ | _ / ________ | 0 | 0

share|improve this answer
4  
+1 Very clever! –  Jason C Feb 24 at 4:04
14  
Been coding JavaScript for years, but have no idea what that is facepalm –  Songo Feb 24 at 10:02
4  
@CarlWitthoft How it works is that _ is a valid variable name in JavaScript - and so is __, ___, ____, ________. –  toothbrush Feb 24 at 14:29
2  
Many thanks. I'll file that (dangerous :-) ) info away for future use. –  Carl Witthoft Feb 24 at 14:42
2  
Who says programmers aren't creative! –  Jonathan Feb 24 at 21:04

C, Twelve Days of Xmas Style

New version:

main(Z,_){Z?(_=Z[" $X,X3Y<X@Z@[<XHZHX,"
"` \\(Z(X0Z0Z8[@X@^8ZHZHX(Z(`#Y(Z(X3[8"
"\\@_8ZHXHXHX(Z(` \\(Z(X0Z0Z8\\@_8ZIXI"
"X(Z(` \\,X0Z0Z8\\@_8ZHZHX,"])?main(0,_
-32),main(Z+1,_):0:(putchar((_>>3)["kt"
"wy~|tE/42"]-37),(_&7)?main(0,_-1):0);}

Output:

FFFFF OOOOO RRRR  TTTTT Y   Y    TTTTT W   W OOOOO
F     O   O R   R   T    Y Y       T   W   W O   O
FFFF  O   O RRRR    T     Y        T   W W W O   O
F     O   O R   R   T     Y        T   WW WW O   O
F     OOOOO R   R   T     Y        T   W   W OOOOO

By the way, also check out my text-to-speech answer.


Original Version:

main(c,z,_){c==1?main(c+1,0,c^c):c==2?
z=_["##$#%&#%#x'%%()&(%%x$%$((&(*%x'%"
"%((&(+%x'#%((&(%#x"],z?z=='x'?main(4,
_,c*5):main(c+1,z,0),main(c,z,_+1):0:c
==3?(_-2)==3?main(_-1,_,32):(main(c+1,
c,((2+c)*(z-35)+_)["six*nine= {   }  "
"   ;      _   ( ) [ 3 ]do {;=0xDA"]==
32?32:043),main(c,z,_+1)):putchar(_);}

The output is:

##### ##### ####  ##### #   #       ##### #   # #####
#     #   # #   #   #    # #          #   #   # #   #
####  #   # ####    #     #           #   # # # #   #
#     #   # #   #   #     #           #   ## ## #   #
#     ##### #   #   #     #           #   #   # #####

Alternate spacing, if you're feeling tacky:

        main(c     ,z,_){c==01?
       main(c+     1,0,c^c):c==2
      ?z=_["#"     "#$#%&#%#x'%%"
     "()&(%%x"             "$%$("
    "(&(""*%x"             "'%%("
   "(&(" "+%x"             "'#%("
  "(&("  "%#x"             ],z ?z
 =='x'?main(4,_     ,c*5):main(c
 +1,z,0),main(c    ,z,_+1):00:c
 ==3?(_+-2)==3?    main(_-1,_,
         32):(     main(
         c+1,c     ,((2+
         c)*(z     -35)+
         _)[""     "six"
         "*ni"     "ne= {   }   "
         "  ;"     "      _   ( "
         ") ["     " 3 ]do {;"]==
         32?32     :043),main(c,z
         ,_+1)     ):putchar(_);}

The program is a single recursive statement. I made it in the style of my favorite obfuscated C program ever, Twelve Days of Christmas (compile, prepare mind to be blown, run).


HOW TO

Also, since this seems as good a place as any, here is a guide describing how to make this type of program. This guide uses the original version above as an example. Aside from the first bit with the block letters, they are general steps:

INITIAL: First, I started by making the block letters:

##### ##### ####  ##### #   #       ##### #   # #####
#     #   # #   #   #    # #          #   #   # #   #
####  #   # ####    #     #           #   # # # #   #
#     #   # #   #   #     #           #   ## ## #   #
#     ##### #   #   #     #           #   #   # #####

I then made a numbered list of the unique patterns in each 5-column character row:

0: *****  
1: **** 
2: *   * 
3:       
4: *     
5:   *   
6:  * *  
7: * * * 
8: ** ** 

And so each of the 5 pixel rows of text becomes a series of 9 numbers:

00000 00000 11111 00000 22222 33333 00000 22222 00000
44444 22222 22222 55555 66666 33333 55555 22222 22222
11111 22222 11111 55555 55555 33333 55555 77777 22222
44444 22222 22222 55555 55555 33333 55555 88888 22222
44444 00000 22222 55555 55555 33333 55555 22222 00000

For obfuscation (and ease of programming) we add the '#' character to the numbers. In the program below, patterns is the array of pixel patterns, and lines is the obfuscated array of pattern codes for each line, terminated by an 'x'. For further obfuscation we define "on" pixels in patterns to be any character that isn't a space; this lets us put more misleading text in pattern:

#include <stdio.h>

char pattern[] = 
  "six*n"
  "ine= "
  "{   }"
  "     "
  ";    "
  "  _  "
  " ( ) "
  "[ 3 ]"
  "do {;";

char lines[] =
  "##$#%&#%#x"
  "'%%()&(%%x"
  "$%$((&(*%x"
  "'%%((&(+%x"
  "'#%((&(%#x";

void printpattern (char c) {
  int n;
  for (n = 0; n < 5; ++ n)
    putchar(pattern[5*(c-'#') + n]==32?32:'#');
  putchar(' ');
}

int main () {
  char *ptr = lines;
  while (*ptr) {
    while (*ptr != 'x')
      printpattern(*(ptr++));
    putchar('\n');
    ++ ptr;
  }
}

STEP 1: The next step involves a few tasks:

  • Remove all loops and use recursion.
  • Change all functions (except main) to the form int function (int, int) and use the same parameter names for each. The reasons will become clear later.
  • Change main to the form int main (int, int, int) and name the last two parameters the same as your function parameter names.
  • Replace all references to string constants with the strings themselves; and use each string only once if possible.
  • The include can be removed; it's unnecessary for int putchar (int).

We can also take advantage of the weird C feature where a[b] is equivalent to b[a] to obfuscate further.

int printpattern (int z, int _) {
  if (_==5)
    putchar(' ');
  else{
    putchar((5*(z-'#') + _)["six*nine= {   }     ;      _   ( ) [ 3 ]do {;"]==32?32:'#');
    printpattern(z, _+1);
  }
  return 0;
}

// z ignored, _ is index
int printtext (int z, int _) {
  z = _["##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x"];
  if (z) {
    if (z == 'x')
      putchar('\n');
    else
      printpattern(z, 0);
    printtext(z, _ + 1); // first parameter arbitrary
  }
  return 0;
}

int main (int c, int z, int _) {
  printtext(0, 0);
}

STEP 2: Next, make use of the ?: and , operators to transform each function into a single return statement. I'm illustrating this separately from the above because this is where things start getting confusing to look at. Remember that putchar() returns an int, and ?: takes precedence over ,:

int printpattern (int z, int _) {
  return _==5 ?
    putchar(' ')
  :
    (putchar((5*(z-'#') + _)["six*nine= {   }     ;      _   ( ) [ 3 ]do {;"]==32?32:'#'),
     printpattern(z, _+1));
}

// z ignored, _ is index
int printtext (int z, int _) {
  return
    z = _["##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x"],
    z ?
      z == 'x' ?
        putchar('\n')
      :
        printpattern(z, 0)
      ,
      printtext(z, _ + 1)
    :
    0;
}

int main (int c, int z, int _) {
  printtext(0, 0);
}

STEP 3: Ok. The next step is a big one. All of the functions are now a single statement of the same form. We can now combine them all into a single function, identifying each one by a number -- essentially turning the entire program into a single recursive function. Note that the first parameter to main will be 1 when the program is run with no arguments, so that should be our initial state.

Also, since our parameter c to main is our state variable, we know its value at all times, and we can obfuscate a little further by replacing integer constants with their values in terms of c (for example, when we know c is 2, we can replace 5 with c+3). Other little obfuscations can be done too (e.g. I replaced '#' with 35 and 043):

int main (int c, int z, int _) {
  switch (c) {
  case 1: // main
    return main(c+1, 0, c^c); // (2, 0, 0)
  case 2: // printtext
    return
    z = _["##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x"],
    z ?
      z == 'x' ?
        putchar('\n')
      :
        main(c+1, z, 0) // c+1==3
      ,
      main(c, z, _ + 1)
    :
    0;
  case 3: // printpattern
    return (_-2)==3 ? // _==5
    putchar(' ')
    :
     (putchar(((2+c)*(z-35) + _)["six*nine= {   }     ;      _   ( ) [ 3 ]do {;"]==32?32:043),
     main(c, z, _+1));
  }
}

STEP 4: Finally, remove the switch block by using a series of ?: operators. We can also remove the int declarations, since C will use them by default, as well as the return itself (which will generate a warning at worst). After this, our program is a single, recursive function with one statement. Pretty cool, right?

Edit: I replaced putchar() with a main and c==4 below; because I just thought of it at the last minute:

main (c, z, _) {
  c == 1 ?
     main(c+1, 0, c^c)
  : c == 2 ?
    z = _["##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x"],
    z ?
      z == 'x' ?
        main(4,_,c*5)
      :
        main(c+1, z, 0) 
      ,
      main(c, z, _ + 1)
    :
    0
  : c==3 ?
    (_-2)==3 ? 
    main(_-1,_,32)
    :
    (main(c+1,c,((2+c)*(z-35) + _)["six*nine= {   }     ;      _   ( ) [ 3 ]do {;"]==32?32:043),
      main(c, z, _+1))
  : // c==4
    putchar(_);
}

If you want to add a little flair, you can use more interesting numbers for c and even base the checks off of other numbers (e.g. for the c==2 case, z is ignored and available, so instead of calling main(2,z,_) you could call main(-97,_,_) and replace c==2 with c<-z). Be creative; the possibilities are endless.

FINISH: The final step, then, is to arrange the text in some creative pattern, and voila! You can adjust the code a little to help with formatting (e.g. I added some extra data at the end of the patterns string in the posted program to help get the line length right). The ladies are sure to be all up ons.

share|improve this answer
    
Should I remove the guide? I kind of like the mystery without it. –  Jason C Feb 24 at 6:58
27  
+1 for the guide –  fuenfundachtzig Feb 24 at 20:35
    
I have updated the answer with a new version that is shorter and prints the letters in the output. The guide is based off the original version (still present). The new version stores the output as RLE data; the first long string is the data. –  Jason C Feb 27 at 6:13
2  
I so want to +1 this answer given you took the time to explain the "how" behind your solution, but it's currently at 42 rep, and I don't want to spoil that. ;) –  Adam Parkin Mar 8 at 0:00
4  
@AdamParkin Haha! Well here, if it gets to 43, it's your job to downvote it. –  Jason C Mar 8 at 0:12

Java

(or C++, the code's almost similar)
Using String functions, so don't forget to include your library!

P.S. I know it's lengthy, but it's supposed to be creative, right? And anyway, it isn't a "lowest-byte-wins".

String s = "Hitchhiker's Guide to the Galaxy";
String s2 = "Don'tPanic";
String s3 = "The Restaurant at the End of the Universe.";

int arthur_dent = s.length();
int ford_prefect = s2.length();
int zooey_deschanel = s3.length();
int vogon_poetry = arthur_dent + ford_prefect;

System.out.println("         " + vogon_poetry + "       " + zooey_deschanel + " " + zooey_deschanel); //in case you're confused, I'm using Zooey to print the big '2', and Vogons to print the big '4'.
System.out.println("       " + vogon_poetry + vogon_poetry + "     " + zooey_deschanel + "     " + zooey_deschanel);
System.out.println("     " + vogon_poetry + "  " + vogon_poetry + "    " + zooey_deschanel + "       " + zooey_deschanel);
System.out.println("   " + vogon_poetry + "    " + vogon_poetry + "            " + zooey_deschanel);
System.out.println(" " + vogon_poetry + "      " + vogon_poetry + "          " + zooey_deschanel);
System.out.println(vogon_poetry + " " + vogon_poetry + " " + vogon_poetry + " DA " + vogon_poetry + "     " + zooey_deschanel);
System.out.println("         " + vogon_poetry + "     " + zooey_deschanel);
System.out.println("         " + vogon_poetry + "    " + zooey_deschanel + " " + zooey_deschanel + " " + zooey_deschanel + " " + zooey_deschanel);

Here's the output:

         42       42 42
       4242     42     42
     42  42    42       42
   42    42            42
 42      42          42
42 42 42 DA 42     42
         42     42
         42    42 42 42 42 

Imagine my misery when I counted and found out that "The Restaurant at the End of the Universe" had 41 characters! :/ Sigh.

share|improve this answer
11  
@user689 D ouglas A dams :) –  mikhailcazi Feb 23 at 9:41
8  
Actually 41 is also DA in a way (D is forth letter, A is the first). Cheer up! –  vadchen Feb 23 at 11:41
7  
4-1 = 3 which means, •_•) ( •_•)>⌐■-■ (⌐■_■) Half Life 3 confirmed. –  wardha-Web Feb 23 at 18:42
14  
The Restaurant at the End of the Universe has 41 characters + "\0" :DDD –  enterx Feb 23 at 22:04
2  
I am only disappointed that the program does not also output some actual Vogon poetry for our, er...painful delight. –  Jonathan Van Matre Feb 24 at 15:39

Seems appropriate:

grep -i "DON'T" /bin/lesspipe | wc -l ; grep -i "PANIC" /usr/share/pyshared/mx/Log.py | head -n 1 | cut -d '=' -f 2 | tr -d ' '

Output:

4
2

Ubuntu 12.04, 64-bit Desktop

share|improve this answer
20  
+1 for don't panic –  Milo Feb 23 at 6:41
    
It would be a bash-ism, but echo $(grep -i ... tr -d ' ') | sed 's/ //g' would put it all on one line. You could also use backquotes instead of the $() form, but that's harder to put in a comment here. –  Mike Renfro Feb 24 at 1:18
    
I'm panicking! Seeing such code that I have no capacitor to understanding is very confuddling. –  Quincunx Feb 24 at 5:46
1  
    
@MikeRenfro How is that a bashishm? $() is specified by the POSIX standard. –  nyuszika7h Jun 1 at 20:37

Mathematica

Take 1

With some work, I ought be able to golf this down a bit. :)

In InputForm:

answer[ultimateQuestion[Life,theUniverse,Everything]] =
  Times[Plus[-1,Limit[Power[Plus[1,Times[Complex[0,1],
  Power[n,-1],Pi]],n],Rule[n,DirectedInfinity[1]]]],Sqrt[-1]^2,
  Times[Rational[1,2],Plus[-1,Fibonacci[4]],Fibonacci[2]],
  Binomial[3,2],LucasL[4]]

In TraditionalForm:

forty two

Testing:

answer[ultimateQuestion[Life,theUniverse,Everything]] 

42


Take 2

Note: The numerals were made as follows.

  • "42" was first printed on the screen in very large font, axes displayed, so that the coordinates of the key points could be identified.
  • Another "4" was drawn a broad straight lines connecting the respective key points. It was superimposed on the previously drawn "4" to check for accuracy. The "2" was drawn as a BSpline curve. Some of the key points, which were now control points, had to be set in position by trial and error to get the desired curves.
  • An third coordinate (always zero) was added to the line and BSplineCurve to enable 3D display.

answer[ultimateQuestion[Life,theUniverse,Everything]]  = 
 Table[With[{v = RotationTransform[θ, {0, 0, 1}][{3, 0, -.2}]},
   Graphics3D[{Thickness[.06], CapForm["Round"],
     Tube[Line[{{-67, 0, -44}, {-30, 0, -44}}], 10],
     Tube[
      Line[{{-25, 0, -12}, {-100, 0, -12}, {-52, 0, 70}, {-45, 0, 70}, {-45, 0, -43}}], 10], 
     Tube[BSplineCurve[l = {{27, 0, 52}, {27, 0, 57}, {57, 0, 85}, {113, 0, 40}, 
     {12, 0, -45}, {35, 0, -45}, {90, 0, -45}, {90, 0, -45}, {92, 0, -35}}], 10]},
     Boxed -> False, PlotRange -> 100, ImageSize -> 250, SphericalRegion -> True, 
     ViewPoint :> v, 
     PlotRangePadding -> 10]],(*{θ,0,2Pi,Pi/24},*){θ, -Pi/2, -Pi/2 + 2 Pi, Pi/24}]

Export["theMeaningOfLife.gif", answer[ultimateQuestion[Life,theUniverse,Everything]] ]

take 2

share|improve this answer
    
Luckily it's not a golfing question :) seems to be a good helping of mathematical creativity in there... –  cormullion Feb 23 at 19:42
1  
Thanks. Mathematica certainly offers lots of options to explore. –  David Carraher Feb 23 at 22:35
1  
Nice; wish I could go back in time and put that graphic on geocities.com/42, haha. –  Jason C Feb 27 at 6:24

Windows calculator

Multiplying Pi with 13.37 and ignoring the decimal :P

Forty-Two

share|improve this answer
13  
+1 because fractions are definitely not 1337. –  Jason C Feb 25 at 11:51
1  
A programmer's calculator would have been better but that calculator don't have (pie) –  Mukul Kumar Mar 1 at 17:06
    
haha, that's the best coincidence evar :D +1 –  Doorknob Mar 1 at 21:54
1  
1337 * math.pi / 100 –  chroman Mar 3 at 2:36
3  
round(1337 * math.pi/100) <-- One small change since pie are round. –  Kevin Mar 13 at 14:50

Python

I guess it only works on Windows 7.

import win32api, win32con, win32gui
from time import time, sleep
import os

w = { 1:[(358, 263), (358, 262), (358, 261), (359, 261), (359, 262), (359, 264), (359, 266), (359, 270), (359, 282),
     (358, 289), (357, 308), (356, 319), (355, 341), (355, 351), (355, 360), (355, 378), (355, 388), (354, 397),
     (354, 406), (354, 422), (354, 428), (354, 436), (354, 438), (354, 439), (354, 440), (355, 440), (356, 439),
     (357, 439), (358, 438), (360, 438), (362, 437), (369, 437), (372, 437), (381, 437), (386, 437), (391, 437),
     (397, 436), (411, 436), (419, 435), (434, 435), (442, 435), (449, 434), (456, 434), (468, 434), (473, 435),
     (480, 436), (483, 436), (485, 436), (487, 437), (488, 437), (488, 438), (488, 439), (487, 440), (486, 440),
     (485, 440), (484, 440), (483, 439), (483, 437), (481, 431), (481, 427), (481, 420), (481, 413), (483, 396),
     (485, 387), (488, 367), (491, 356), (493, 345), (500, 321), (503, 310), (507, 299), (514, 280), (517, 272),
     (520, 266), (523, 260), (524, 258), (524, 259), (524, 261), (524, 265), (524, 269), (523, 275), (522, 289),
     (521, 297), (518, 315), (516, 324), (515, 334), (513, 345), (509, 368), (507, 382), (502, 411), (500, 426),
     (498, 440), (495, 453), (491, 478), (489, 491), (485, 517), (483, 530), (481, 542), (479, 552), (476, 570),
     (475, 577), (474, 588), (473, 592), (473, 595), (473, 597), (473, 600), (473, 601), (473, 602), (473, 601),
     (474, 599), (475, 597), (476, 594), (478, 587)],
  2:[(632, 305), (634, 306), (636, 309), (639, 314), (641, 319), (645, 330), (647, 337), (649, 353), (649, 362),
     (649, 372), (649, 384), (645, 409), (639, 436), (636, 448), (632, 459), (627, 470), (623, 479), (613, 497),
     (608, 503), (599, 512), (595, 514), (591, 514), (587, 513), (581, 504), (578, 498), (576, 483), (575, 476),
     (575, 469), (579, 454), (582, 447), (591, 436), (595, 432), (600, 430), (605, 429), (617, 432), (624, 437),
     (639, 448), (646, 455), (654, 461), (662, 469), (679, 484), (686, 491), (702, 504), (710, 509), (718, 512),
     (727, 514), (744, 515), (752, 515), (767, 512), (774, 510), (779, 508), (783, 505), (788, 499), (789, 495),
     (789, 486)] }

def d( x1, y1, x2, y2 ):
    win32api.SetCursorPos((x1, y1))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    win32api.SetCursorPos((x2, y2))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
    sleep(0.01)

def p( l1 ):
    l2 = [""]
    l2.extend(l1)
    l1.append("")
    l3 = zip(l2, l1)
    l3.pop(0)
    l3.pop(-1)
    for n in l3:
        d(n[0][0], n[0][1], n[1][0], n[1][1])

os.startfile("C:\Windows\system32\mspaint.exe")
sleep(0.5)
win32gui.ShowWindow(win32gui.GetForegroundWindow(), win32con.SW_MAXIMIZE)
sleep(0.5)

for n in w:
    p(w[n])

The result is opening Paint and painting 42 as free hand.

42

share|improve this answer
    
I don't have win32api :( Wanted to see that... Still +1 though :D –  Timtech Feb 26 at 22:31
    
I don't use windows, so I can't run it; but your way is brilliant. –  pushpen.paul Jul 31 at 19:01

I'm feeling lazy.

Python

t
h
e
a
n
s
w
e
r
t
o

l
i
f
e

t
h
e
u
n
i
v
e
r
s
e

a
n
d
e
v
e
r
y
t
h
i
n
g:

Output:

  File "golf.py", line 42
    g:
     ^
SyntaxError: invalid syntax
share|improve this answer
2  
First time I have seen an error as the desired output. +1 for originality. –  Milo Mar 2 at 8:28

Java (Swing)

This will display a frame drawing the answer. It only uses 42 for values.

public        class         FourtyTwo{ public
static         void         main(String[]args)
{  new        javax                    .swing.
JFrame        () {{                    setSize
(42 /(        42/42                    +42/42)
*42/ (        42/42                    +42/42)
,42/(42/ 42+42/42)*         42/(42/42+42/42));
}public void paint(         java.awt .Graphics
  g){g.drawPolygon(         new int[]{42,42,42
              + 42+         42,42+
              42+42         ,42+42
              +42 +         42,42+
              42+42         +42,42
              + 42+         42,42+42+42,42+42,
              42+42         },new int[]{42,42+
              42+42         +42,42+42+42+42,42

+42+42+42+42+42,                  42+42+
42+42+42+42,42,42,               42+42+42
,42 +        42+42              ,42}, (42/
42+42        /42)*              (42/  42 +
42/42        + 42/             42 +    42 /
42+42        /42))            ;g.drawPolygon
( new        int[]           {42+42+42+42+42,
42+42        +42 +           42+42      , 42+
42+42        + 42+          42+42        + 42,
42+42        +42 +          42+42        +42 +
42,42+42+42+42+42,         42+42          + 42+
42+42,42+ 42+42+           42+42          +42 +

42+42,42+42+42+42+42+42+42+42,42+42+42+42+42+42,
42+42+42+42+42+42,42+42+42+42+42+42+42+42,42+42+
42+42+42+42+42+42},new int[]{42,42 +42,42+42,42+
42+42,42+42+42,42+42+42+42+42+42,42+42+42+42+42+
42,42+42+42+42+42,42+42+42+42+42,42+42+42+42,42+
42+42+42,42},(42/42+42/42+42/42)*((42/42+42/42)*
(42/42+42/ 42)));};}.setVisible(42*42*42!=42);}}
share|improve this answer
8  
+1 for the "I-just-spent-a-ton-of-time-formatting-this-and-I-really-don't-feel-like-working‌​-the-leftovers-in" block at the bottom, haha. –  Jason C Feb 27 at 9:16
3  
@JasonC That's exactly what I thought! ;D Tomorrow, I'll work on a program which formats code to ASCII art and I'll be rich! –  bobbel Feb 27 at 9:20
    
I started to do this with mine and quickly gave up. Nice job. –  Chief Two Pencils Feb 28 at 9:40

Ruby

It is well known what you get if you multiply six by nine. This gives one solution:

puts (6 * 9).to_s(13)

Python

A variant of Tupper's self-referential formula:

# Based loosely on http://www.pypedia.com/index.php/Tupper_self_referential_formula
k = 17 * (
    (2**17)**0 * 0b11100000000000000 +
    (2**17)**1 * 0b00100000000000000 +
    (2**17)**2 * 0b00100000000000000 +
    (2**17)**3 * 0b11111000000000000 +
    (2**17)**4 * 0b00100000000000000 +
    (2**17)**5 * 0b00000000000000000 +
    (2**17)**6 * 0b01001000000000000 +
    (2**17)**7 * 0b10011000000000000 +
    (2**17)**8 * 0b10011000000000000 +
    (2**17)**9 * 0b01101000000000000 +
0)
# or if you prefer, k=int('4j6h0e8x4fl0deshova5fsap4gq0glw0lc',36)

def f(x,y):
    return y // 17 // 2**(x * 17 + y % 17) % 2 > 0.5
for y in range(k + 16, k + 11, -1):
    print("".join(" @"[f(x, y)] for x in range(10)))

Output:

@  @   @@ 
@  @  @  @
@@@@@    @
   @   @@ 
   @  @@@@
share|improve this answer
1  
Unfortunately, as your Wikipedia link points out, DNA rejects the first method of producing 42: "I may be a sorry case, but I don't write jokes in base 13." –  L Spice Mar 3 at 2:24

Mathematica

WolframAlpha["meaning of life", {{"Result", 1}, "Content"}]

42

though I think it's cheating, really, since it's hard-coded. And not very creative, on my part... :)

share|improve this answer

Forth:

SCR # 1
 0 ( FORTY-TWO @ ES-FORTH )
 1 HEX 0 24 -31 21 -31 31 -31
 2 31 -14 51 11 -11 51 11 -11 23 31
 3 : T SWAP 0 DO DUP EMIT LOOP DROP ;
 4 : K BEGIN DUP WHILE DUP 0< IF CR
 5  ABS THEN 10 /MOD 20 T A0 T
 6  REPEAT DROP ;
 7 K CR

That 1 LOAD outputs:

   █  ███
 █ █     █
 █ █     █
 ████   █
   █   █
   █  █
   █  ████
share|improve this answer

R

sum(as.numeric(factor(unlist(strsplit(gsub(" |[.]","","D. ADAMS"),"")),levels=LETTERS)))

Result:

42
share|improve this answer

C++

cout<<"....-"<<" "<<"..---";

Morse code ;)

share|improve this answer

Javascript

alert((!![]+ -~[])*(!![]+ -~[])+""+(!![]+ -~[]))
share|improve this answer
3  
Another one that gave me a WTF moment until I realised true == 1. –  George Reith Feb 25 at 7:53
7  
ALERT! WEIRD ASCII CATERPILLARS! USE EXTREME CAUTION! –  Jason C Feb 27 at 9:15

LMGTFY

http://bit.ly/1ldqJ8w

Short enough that I had to type this to reach the minimum character count...

share|improve this answer
17  
simply divide by newton –  Bergi Feb 24 at 3:54

dc

$ dc <<< "1 8 sc 1 5 lc *++p"
42

Trying to multiply 1+8 and 5+1 to get 42. It looks like that ignorance of operator precedence led to 42.


Python

>>> p = lambda x: x%2!=0 and True<<x
>>> sum(p(i) for i in range(0,6))

Output: 42


bash

(Multiplying 6 by 9)

$ echo "obase=13;6*9"|bc|figlet
 _  _  ____
| || ||___ \
| || |_ __) |
|__   _/ __/
   |_||_____|

C

#include <stdio.h>
int main(){printf("%d",fprintf(fopen("/dev/null","w"), "so-popularity-contest\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"));}

Output: 42

  • Did you notice the use of backspace characters?
  • Do you know what do those result in?
share|improve this answer
    
No ..please explain! –  Antonio Ragagnin Feb 23 at 18:44
    
The backspace characters pad the string to a length of 42 bytes. So first fopen is used to open the null device for write access. Then fprintf writes 42 bytes to null, returning the numbers of bytes written. Finally that 42 is formatted by the printf function's "%d" format string to display 42. I like it! –  CasaDeRobison Feb 24 at 9:28

Java

public class MainProgram {    
    public static void main(String[] args) {
        int[] the      = { 'T', 'h', 'e' };
        int[] most     = { 'M', 'o', 's', 't' };
        int[] creative = { 'C', 'r', 'e', 'a', 't', 'i', 'v', 'e' };
        int[] way      = { 'W', 'a', 'y' };
        int question   = '?';

        double x = -3.18906605923E-2;

        int The      = 0;
        int Most     = 0;
        int Creative = 0;
        int Way      = 0;

        for(int i : the) {
            The += i;
        }
        for(int i : most) {
            Most += i;
        }
        for(int i : creative) {
            Creative += i;
        }
        for(int i : way) {
            Way += i;
        }
        System.out.println((int)((The*x)-(Most*x)-(Creative*x)-(Way*x)-(question*x)));      
    }//SSCE
}//good1

Output:

42

share|improve this answer
    
+1 for employing an interesting linear equation, good job! –  awashburn Jun 26 at 18:48

PHP version:

 echo strlen("Douglas Adams")+strlen("born on")+array_sum(array(1,1,0,3,1,9,5,2));
 /* array(1,1,0,3,1,9,5,2) => March 11, 1952 */

JavaScript version:

 console.log("Douglas Adams".length + "born on".length + [1,1,0,3,1,9,5,2].reduce(function(previousValue, currentValue, index, array){return previousValue + currentValue;}));

 /* [1,1,0,3,1,9,5,2] => March 11, 1952 */

Output:

 42
share|improve this answer
2  
I’ll never understand how any sane human can write a date in this order. The fact that you have to put a comment there, proves how useless this format is. –  canaaerus Feb 24 at 11:48
1  
@canaaerus I have just used the date in a specific format so that it can be processed by a program to arrive at 42. I tried various other human readable ways, and this was the closest that I could transform the date to arrive at the solution. –  palerdot Feb 24 at 12:00
18  
@canaaerus I'll never understand how Americans can write dates as mm/dd/yy, either. If you say 04/03/11, I'd read it as the 4th of March, 2011 - not the 3rd of April. –  toothbrush Feb 24 at 15:02
6  
@palerdot. As far as I know, only US-Americans (and occasionally Canadians) write dates in that weird, confusing, "middle-endian" manner. –  TRiG Feb 24 at 18:57
2  
@TRiG: What do you expect? We, aside from those of us in science and engineering fields, shun the more intuitive and logical metric system too.?. –  Chief Two Pencils Feb 25 at 20:46

SWI-Prolog, anyone?

?- X.

Output:

% ... 1,000,000 ............ 10,000,000 years later
% 
%       >> 42 << (last release gives the question)

This is even lazier than the Mathematica-calling-Wolfram-Alpha one, but hey!

share|improve this answer
3  
Welcome to Code-Golf! Don't forget to add an explanation on why this answer is creative! –  Quincunx Feb 24 at 5:48
1  
@Quincunx It's an easter egg in SWI-Prolog. –  svick Feb 24 at 14:30

Linux shell

Here’s something I wrote in 1999 and used as my Usenet signature back then.

echo "what is the universe"|tr "a-z " 0-7-0-729|sed 's/9.//g;s/-/+/'|bc

Edit: Ha! This was the 42nd answer.

share|improve this answer

Brainf**k

- [   --
- -     -
>+<]  >+
  .   --.
share|improve this answer
    
Does this depend on an overflow in the interpreter? –  Cruncher Feb 25 at 16:38
    
Yeah, looks like it assumes overflow to 255. 255/5 = 51 + 1 = 52 which is character code for 4. I don't think all interpreters do this, but +1 –  Cruncher Feb 25 at 16:41
    
@Cruncher It needs 8-bit wrapping cells. This is the most common type. –  Timtech Feb 25 at 23:50

PHP

Ask WolframAlpha. Here's some code that uses the WolframAlpha API to retrieve the result of a specific search query:

<?php

$searchTerm = "What's the answer to life, universe and everything?";

$url = 'http://api.wolframalpha.com/v2/query?appid=APLTT9-9WG78GYE65&input='.urlencode($searchTerm);
$xml = file_get_contents($url);

$xmlObj = simplexml_load_string($xml);
$plaintext = $xmlObj->xpath('//plaintext')[1];
$answer = preg_replace('/\D/', '', $plaintext);

echo $answer;

Output:

42

Working demo

share|improve this answer
1  
Going to the network when you really don't need to doesn't seem very creative to me, especially since it's a common anti-pattern. –  Blacklight Shining Feb 23 at 14:02

C++

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)66<<(char)73<<(char)82;
    cout<<(char)84<<(char)72<<(char)32;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)32<<(char)68<<(char)69;
    cout<<(char)65<<(char)84<<(char)72;
    cout<<(char)32<<(char)32<<'\n';
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)32<<(char)32<<(char)95;
    cout<<(char)95<<(char)95<<(char)32;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)32<<(char)95<<(char)95;
    cout<<(char)95<<(char)95<<(char)95;
    cout<<(char)95<<(char)32<<'\n';
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)32<<(char)47<<(char)32;
    cout<<(char)32<<(char)32<<(char)124;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)124<<(char)32<<(char)32;
    cout<<(char)95<<(char)95<<(char)32;
    cout<<(char)32<<(char)124<<'\n';
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)47<<(char)32<<(char)47;
    cout<<(char)124<<(char)32<<(char)124;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)124<<(char)95<<(char)124;
    cout<<(char)32<<(char)32<<(char)124;
    cout<<(char)32<<(char)124<<'\n';
    cout<<(char)32<<(char)32<<(char)47;
    cout<<(char)32<<(char)47<<(char)32;
    cout<<(char)124<<(char)49<<(char)124;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)32<<(char)32<<(char)47;
    cout<<(char)50<<(char)124<<'\n';
    cout<<(char)32<<(char)47<<(char)32;
    cout<<(char)47<<(char)32<<(char)32;
    cout<<(char)124<<(char)57<<(char)124;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)84<<(char)79<<(char)32;
    cout<<(char)32<<(char)47<<(char)48;
    cout<<(char)47<<(char)32<<'\n';
    cout<<(char)47<<(char)32<<(char)47;
    cout<<(char)95<<(char)95<<(char)95;
    cout<<(char)124<<(char)53<<(char)124;
    cout<<(char)95<<(char)95<<(char)32;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)47<<(char)48<<(char)47;
    cout<<(char)32<<(char)32<<'\n';
    cout<<(char)124<<(char)95<<(char)95;
    cout<<(char)95<<(char)95<<(char)95;
    cout<<(char)124<<(char)50<<(char)124;
    cout<<(char)95<<(char)95<<(char)124;
    cout<<(char)32<<(char)32<<(char)47;
    cout<<(char)49<<(char)47<<(char)32;
    cout<<(char)32<<(char)32<<'\n';
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)124<<(char)32<<(char)124;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)32<<(char)47<<(char)32;
    cout<<(char)47<<(char)32<<(char)32;
    cout<<(char)32<<(char)32<<'\n';
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)124<<(char)32<<(char)124;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)47<<(char)32<<(char)47;
    cout<<(char)95<<(char)95<<(char)95;
    cout<<(char)95<<(char)32<<'\n';
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)32<<(char)32<<(char)32;
    cout<<(char)124<<(char)95<<(char)124;
    cout<<(char)32<<(char)32<<(char)124;
    cout<<(char)95<<(char)95<<(char)95;
    cout<<(char)95<<(char)95<<(char)95;
    cout<<(char)95<<(char)124<<'\n';
    getch();
    return 0;
}  

output

enter image description here

share|improve this answer
    
Output: 1>c:\users\1 and 2 is 3\documents\visual studio 2012\projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp(87‌​): error C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details. –  hosch250 Feb 23 at 19:27
    
Cool, once I fixed it. –  hosch250 Feb 23 at 19:28
    
@user2509848 what was the error ? –  Mukul Kumar Feb 24 at 16:48
    
Posted it in the first comment. Visual Studio wanted getch to be _getch instead. –  hosch250 Feb 24 at 16:49
    
Oh but the code is right for the compiler I use –  Mukul Kumar Feb 24 at 16:54

JavaScript

The ASCII code for *, which for most programmers stands for "everything", is 42. +!"The End of the Universe" evaluates to 0.

String.prototype.answer = function() { alert(this.charCodeAt(+!"The End of the Universe")); };
'*'.answer();
share|improve this answer
2  
I prefer to think of it as a Kleene Star. –  primo Feb 25 at 9:39

Bash – 42 bytes

  1. Vertical Version

    #!/bin/bash
    echo $((2#100))
    echo $((2#10))
    

    Yep, that's exactly 42 bytes of sourcecode to output:

    4
    2
    
  2. Horizontal Version

    After I posted the “Vertical Version”, Glenn correctly noted in a comment that you could write both numbers on a single line too by writing echo $((2#00100))$((2#00010)). Yet, the prepended zeros wouldn't depict full bytes (which would expect 8 binary characters per byte), which was the main reason why I initially opted-out of posting that solution. Also, Glenn's suggestion merely uses 41 bytes, which is not what I intended.

    Nevertheless, to add a horizontal alternative which – again – uses 42 bytes of sourcecode:

    #!/bin/bash
    echo $((2#000100))$((2#00010))
    

    Note that this is almost the same as what Glenn suggested, but with an added 0 in the first binary representation, which make the sourcecode exactly fit 42 bytes. It's output will be:

    42
    
share|improve this answer
    
I count 44 bytes. –  Doorknob Feb 23 at 22:15
    
@Doorknob Then you should count again... 11 + \n + 15 + \n + 14 = 42 bytes including the two newlines. –  e-sushi Feb 23 at 23:26
    
Turns out your code had trailing spaces at the end of the lines, which threw off my automatic length counter. I edited them out –  Doorknob Feb 23 at 23:29
    
Hmmm, must have been SE modding my copy-and-paste. Thanks for killing two invisible chars then. ;) –  e-sushi Feb 23 at 23:33
3  
Still 42 bytes of source code, but writes 42 on one line. Replace the two echo statements with one: echo $((2#00100))$((2#00010)) –  Glenn Randers-Pehrson Feb 24 at 3:58

JavaScript

window.location = "https://www.google.nl/search?q=the+answer+to+life+the+universe+and+everything";

Outputs 42.

share|improve this answer

protected by Community Feb 28 at 22:57

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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