Most creative way to display 42

385

166

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.

You could print it in the log, via some convoluted method, or display it as ASCII art, or anything! Just come up with a creative method of displaying 42.

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

Milo

Posted 12 years ago

Reputation: 3 082

1A fortitudinous challenge.... – keshlam – 12 years ago

@keshlam I guess...if one considers this challenge to be brave and courageous then yeah I guess it is :) – Milo – 12 years ago

@keshlam I know I was just messing with you :) – Milo – 12 years ago

6The 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 Stafusa – 12 years ago

1On any other SE site, this would be closed as "too broad". – Dan Dascalescu – 12 years ago

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 – 12 years ago

9The question should remain at 42 votes. – Zero Fiber – 12 years ago

2This question had just 42 answers! – bobbel – 12 years ago

28Marvin The Robot "I would post my brilliant answer, but you would probably down vote it. Being right all the time is so depressing." – Reactgular – 12 years ago

@SampritiPanda - too late! – TheDoctor – 12 years ago

1Everybody un-upvote! – Zero Fiber – 12 years ago

3Can we get 42 favorites? – Milo – 12 years ago

@Milo: fav-count is at 42 now. :) – Aschratt – 12 years ago

First dibs on audio! – Jason C – 12 years ago

1@Aschratt Someone favourited past 42. Everyone unfavourite now to get down to 42! – Cruncher – 12 years ago

@Cruncher What if you guys unfavored it to 42 then someone else unfavored it to 41? Or favored it back to 43? :P – John Odom – 12 years ago

Make votes and favorites 42 and freeze the question. – Zero Fiber – 12 years ago

@SampritiPanda I'm not sure questions can be frozen so solid as to prevent favouriting. Unless they are deleted. – Mr Lister – 12 years ago

2Haha, I'm the 42nd person to earn the Civic Duty badge... and I got it by voting on this question! That's just perfect :D – Doorknob – 12 years ago

42k views lol :D – Silviu Burcea – 12 years ago

42 kviews, and the question above (the one about reversing an integer) has 42 answers... – Oberon – 12 years ago

Pi! (314 votes) – Milo – 11 years ago

Answers

842

Double Brainfuck

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

which outputs...

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

which outputs...

6*7=42

grovesNL

Posted 12 years ago

Reputation: 6 736

@grovesNL how.... how do you.... I am at a complete loss. – IronManMark20 – 11 years ago

1This has got to be both the most upvoted and the best answer of all time on any SE site. – ASCIIThenANSI – 11 years ago

3While being the worst dressed code in the universe, brilliant! – HTDutchy – 12 years ago

2Does the first output occur in that very shape? :O – mikhailcazi – 12 years ago

92I always thought something was fundamentally wrong with the universe. – mfitzp – 12 years ago

1@mfitzp Yeah, especially since mice were appointed to find the Question. o_O – mikhailcazi – 12 years ago

5@mikhailcazi: Yes, it prints newlines and spaces to create that output. Run it in an online interpreter if you want to see. – grovesNL – 12 years ago

147It should be 6*9=42. – Proxy – 12 years ago

477=49, so, 49-7=67=42 – Ismael Miguel – 12 years ago

17@Proxy: True, but sometimes those references are lost on the viewers, even despite the context... ;-) – grovesNL – 12 years ago

19@IsmaelMiguel: That's so base 10 of you... – Dennis – 12 years ago

26I upvoted the whole question just so people would see this answer. – Michael Stern – 12 years ago

3@IsmaelMiguel Not binary. Base 13! xD – mikhailcazi – 12 years ago

6I still don't know the question.. but I think you may have just found the question to the ultimate question to life the universe and everything. – James Webster – 12 years ago

1One word: inception. – javatarz – 12 years ago

2If this is inception... can it go another layer to get the 42 that makes the 42 that makes the 42 that makes the 42? – WernerCD – 12 years ago

1@WernerCD: rright. Let's just write TheApp that given an integer N emits a Brainfuck code that upon running will emit strictly different Brainfuck code that will be output-equivalent to running TheApp with (N-1) value. – quetzalcoatl – 12 years ago

2@WernerCD why not go further with 42 steps of 42s that make 42s? – Gorkk – 12 years ago

@Gorkk OK, do it! – Toothbrush – 12 years ago

7I logged on to this site for the first time just to upvote this awesome answer. – J.R. – 12 years ago

7@WernerCD I did consider going another level, but I was afraid I'd never stop. – grovesNL – 12 years ago

11And I thought Brainfuck was the most useless language. I never once considered the horror of Double Brainfuck. +1 for masochism. – Basic – 12 years ago

4

I think this might be the 2nd highest rated answer ever on codegolf; we'll have to wait for next week's data snapshot to check.

– Jason C – 12 years ago

@JasonC Thanks for that information. This was only my second post on this board. I had no idea it would be this popular. – grovesNL – 12 years ago

3@grovesNL That's because it's totally kick-ass! BTW I just noticed that I accidentally edited that query to show top questions not answers, and saved it. Fixed to show top answers again. We'll have to go talk smack on the Happy New Year post. – Jason C – 12 years ago

5Good. Now write a Brainfuck program that spells out a huge 42 and outputs a Brainfuck program that spells out a larger 42. – Blacklight Shining – 12 years ago

1@grovesNL Snapshots updated. It's official, lol. – Jason C – 12 years ago

1@JasonC: There's still time to reach number one... Maybe I should add another level of 42 – grovesNL – 12 years ago

Such avatar! Wow. So doge! (Look at mine ;) – Reinstate Monica Cellio – 12 years ago

@BlacklightShining I did half the work: here is a Python script that outputs a Brainfuck program that outputs the Python script's input. Now all we need is a program that formats the output as 42. :D

– Emil Lundberg – 11 years ago

329

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.

Mr Lister

Posted 12 years ago

Reputation: 3 668

15that is awesome – ASKASK – 12 years ago

41I love the use of #define to get the math "right" ^^. You're a hoopy frood. – Olivier Dulac – 12 years ago

cc: @OlivierDulac But how does it get the math right? I've never worked C, but have worked on C++. #define isn't something that I've encountered before. – mikhailcazi – 12 years ago

35@mikhailcazi: The preprocessor will replace those constants literally, so six*nine becomes 1+5*8+1 which is 42. Well done Mr Lister. – bodo – 12 years ago

7@canaaerus Holy shit, that is genius. Bravo, Mr Lister! – mikhailcazi – 12 years ago

4@mikhailcazi #define works in C++ exactly the same way as in C. – Mr Lister – 12 years ago

3

This is amusing, but it is actually at least 12 years old. I know I've already seen it somewhere around 2005-2007, but I was able to find someone who included it as a joke in a header as far back as 2001 here.

– hvd – 12 years ago

@hvd But I never tried to pass it off as my own invention. – Mr Lister – 12 years ago

I agree with @MrLister: you should try to find the oldest possible reference and quote it / link it. I also remember seeing it in a similar form as far back as 2002, and I'm pretty sure it existed way before this time. – haylem – 12 years ago

@haylem I think I saw it on Usenet, in 1998 or earlier, but I have not found any earlier references than the one hvd pointed to. – Mr Lister – 12 years ago

2

Oh, yes, Usenet! Here's one from 1993.

– hvd – 12 years ago

@hvd: Thanks! I spent a good hour trying to dig something like that up w/o success. I can now move on peacefully! Actually I think that what I had seen was a copy of this exact email on an internal newsgroup at my engineering school while I was student. – haylem – 12 years ago

So the earth have a #define error like this! – PhoneixS – 12 years ago

137

Brainfuck

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

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

When run, it will print 42, of course.

Donarsson

Posted 12 years ago

Reputation: 1 191

6Not 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. – Isiah Meadows – 12 years ago

64I have to admit, the font styling of the code to show "42" is gorgeous... – WallyWest – 12 years ago

15I wish they wrote the Linux kernel in brainfuck. – devnull – 12 years ago

10

Sadly, you've been outdone by grovesNL.

– Blacklight Shining – 12 years ago

6I 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 – 12 years ago

@Donarsson I like your font as well. I based my first "42" off of Calibri, by manually spacing the characters/creating newlines after I had wrote the code. I'm not particularly skilled with ASCII art. On the plus side, all of the characters in mine are meaningful. – grovesNL – 12 years ago

1I did the .nfo files for a release group in the past, so I have a bit practice. My font was originally supposed to be based on the Ubuntu font, but the subtle rounding didn't work well, so I came up with this. But I really like your solution better overall and it obviously took more effort. – Donarsson – 12 years ago

2@impinball i want to upvote your comment, but that would make it 43 upvotes, which is totally unacceptable. – Filip Haglund – 12 years ago

133

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

Toothbrush

Posted 12 years ago

Reputation: 3 197

"For the people who don't understand, it actually evaluates the following" - ha ha, lol. +1 – theonlygusti – 11 years ago

17Been coding JavaScript for years, but have no idea what that is facepalm – Songo – 12 years ago

I'm no expert in Markdown, PHP, or any of that, so I guess what I'm asking is: would your code work in a plain old "vanilla" html web page, with little more than <html> and <head> tags? – Carl Witthoft – 12 years ago

@CarlWitthoft It's plain JavaScript. Try it in your browser's console; otherwise, see a full example with an alert that I just created on JSFiddle.

– Toothbrush – 12 years ago

5@CarlWitthoft How it works is that _ is a valid variable name in JavaScript - and so is __, ___, ____, ________. – Toothbrush – 12 years ago

@CarlWitthoft | 0 does a bitwise or with 0.

– Toothbrush – 12 years ago

3Many thanks. I'll file that (dangerous :-) ) info away for future use. – Carl Witthoft – 12 years ago

2Who says programmers aren't creative! – Jonathan – 12 years ago

1As someone who writes a lot of JavaScript daily... well done, you really stumped me for a while. I would of happily browsed past it and assumed some esolang. – George Reith – 12 years ago

1

@Songo: Look at this: http://jsfiddle.net/kimiliini/EUtZ6/

– user13500 – 12 years ago

@user13500 That's great. – Toothbrush – 12 years ago

1The explanation explains nothing. I love it. – Tortoise – 11 years ago

76

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.

Jason C

Posted 12 years ago

Reputation: 6 253

Should I remove the guide? I kind of like the mystery without it. – Jason C – 12 years ago

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 – 12 years ago

2I 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 – 12 years ago

4@AdamParkin Haha! Well here, if it gets to 43, it's your job to downvote it. – Jason C – 12 years ago

66

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

cjfaure

Posted 12 years ago

Reputation: 4 213

15First time I have seen an error as the desired output. +1 for originality. – Milo – 12 years ago

63

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.

mikhailcazi

Posted 12 years ago

Reputation: 779

Make it "The Restaurant at the End of the Universes" ... now it is 42 characters and verbally correct too. – Deepak Kamat – 10 years ago

@DeepakKamat but that's not the title of the book! :D – mikhailcazi – 10 years ago

2why is there a 'DA' in the output? is it intentional? – Mhmd – 12 years ago

14@user689 D ouglas A dams :) – mikhailcazi – 12 years ago

oh that's great – Mhmd – 12 years ago

9Actually 41 is also DA in a way (D is forth letter, A is the first). Cheer up! – vadchen – 12 years ago

1@vadchen Hahaha that's great! :D My misery was only momentary, but thanks! ;) – mikhailcazi – 12 years ago

114-1 = 3 which means, •_•) ( •_•)>⌐■-■ (⌐■_■) Half Life 3 confirmed. – Mohd Abdul Mujib – 12 years ago

17The Restaurant at the End of the Universe has 41 characters + "\0" :DDD – enterx – 12 years ago

Please, add the public class Show42 { public static void main(String[] args) { ... } }, so this can be considered a complete program. – Victor Stafusa – 12 years ago

Why Zooey Deschanel? – pandubear – 12 years ago

2@pandubear Because I love Zooey Deschanel :D And she plays Tricia McMillan (aka Trillian Astra) in the Hitchhiker movie :) – mikhailcazi – 12 years ago

@Victor Oh, I didn't realise that I had to write an entire program. Snippets aren't allowed? – mikhailcazi – 12 years ago

Valid reason. I love her too. Carry on. – pandubear – 12 years ago

Could change it to the "Ends", no one will notice, XD – SGM1 – 12 years ago

@SGM1 Haha I feel less guilty using a full-stop at the end. xD – mikhailcazi – 12 years ago

2I am only disappointed that the program does not also output some actual Vogon poetry for our, er...painful delight. – Jonathan Van Matre – 12 years ago

@mikhailcazi Yes they are allowed, but the entire program is better for people who might want to run it. Further, for code-golfing challenges (not this case) there are people who post only snippets and other people considers this as cheating, resulting in a needless discussion. – Victor Stafusa – 12 years ago

1@JonathanVanMatre Well, I actually thought about it: arranging "O freddled Gruntbuggly..." into the shape of 42. On popular demand, I could still do that. Or, if people want it, I could do something with Paula Nancy Millstone Jennings' poetry, of course! xD – mikhailcazi – 12 years ago

I just realised that I did vogon_poetry = arthur_dent + ford_prefect, and in the book, the Vogons torture Arthur and Ford with their poetry! :D – mikhailcazi – 12 years ago

Just a note: the import statement is superfluous – java.lang is auto-imported. – Paŭlo Ebermann – 12 years ago

@PaŭloEbermann Oh, it is? I didn't know that. Whenever we used String functions (at school) like charAt and stuff we were told to import the lang package. Anyway, thanks! – mikhailcazi – 12 years ago

59

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

DavidC

Posted 12 years ago

Reputation: 24 524

1Luckily it's not a golfing question :) seems to be a good helping of mathematical creativity in there... – cormullion – 12 years ago

1Thanks. Mathematica certainly offers lots of options to explore. – DavidC – 12 years ago

3Nice; wish I could go back in time and put that graphic on geocities.com/42, haha. – Jason C – 12 years ago

57

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

Kevin

Posted 12 years ago

Reputation: 3 123

23+1 for don't panic – Milo – 12 years ago

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 – 12 years ago

@MikeRenfro How is that a bashishm? $() is specified by the POSIX standard.

– nyuszika7h – 11 years ago

Correct, I'm obviously out of date. Last time I checked (many years ago), I thought it was. May have been wrong then, too. – Mike Renfro – 11 years ago

45

Windows calculator

Multiplying Pi with 13.37 and ignoring the decimal :P

Forty-Two

Aschratt

Posted 12 years ago

Reputation: 699

17+1 because fractions are definitely not 1337. – Jason C – 12 years ago

1A programmer's calculator would have been better but that calculator don't have (pie) – Mukul Kumar – 12 years ago

11337 * math.pi / 100 – chroman – 12 years ago

11round(1337 * math.pi/100) <-- One small change since pie are round. – Kevin – 12 years ago

41

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

f.rodrigues

Posted 12 years ago

Reputation: 645

3I wanted to upvote this, but this has exactly 42 upvotes, don't want to mess that up. – Rohcana – 10 years ago

1I don't have win32api :( Wanted to see that... Still +1 though :D – Timtech – 12 years ago

I don't use windows, so I can't run it; but your way is brilliant. – xxx--- – 11 years ago

39

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);}}

bobbel

Posted 12 years ago

Reputation: 1 037

14+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 – 12 years ago

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 – 12 years ago

I started to do this with mine and quickly gave up. Nice job. – ChiefTwoPencils – 12 years ago

28

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:

@  @   @@ 
@  @  @  @
@@@@@    @
   @   @@ 
   @  @@@@

Mechanical snail

Posted 12 years ago

Reputation: 2 213

2Unfortunately, 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." – LSpice – 12 years ago

28

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... :)

cormullion

Posted 12 years ago

Reputation: 569

26

Javascript

alert((!![]+ -~[])*(!![]+ -~[])+""+(!![]+ -~[]))

Clyde Lobo

Posted 12 years ago

Reputation: 1 395

Use [] instead of "" ([] == '')! alert((!![]+-~[])*(!![]+-~[])+[]+(!![]+-~[])) – Toothbrush – 10 years ago

(!-[] === true) && (!~[] === false). You can also substitute {} for []. – Toothbrush – 10 years ago

1How about (!!{}+!-[]<<-~{})+[]+(!-[]+-~[])? – Toothbrush – 10 years ago

3Another one that gave me a WTF moment until I realised true == 1. – George Reith – 12 years ago

12ALERT! WEIRD ASCII CATERPILLARS! USE EXTREME CAUTION! – Jason C – 12 years ago

24

LMGTFY

http://bit.ly/1ldqJ8w

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

Jason C

Posted 12 years ago

Reputation: 6 253

19simply divide by newton – Bergi – 12 years ago

23

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:

   █  ███
 █ █     █
 █ █     █
 ████   █
   █   █
   █  █
   █  ████

Francisco

Posted 12 years ago

Reputation: 231

22

C++

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

Morse code ;)

user85837

Posted 12 years ago

Reputation: 335

21

R

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

Result:

42

vadchen

Posted 12 years ago

Reputation: 311

18

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

ChiefTwoPencils

Posted 12 years ago

Reputation: 281

2+1 for employing an interesting linear equation, good job! – recursion.ninja – 11 years ago

17

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!

YellPika

Posted 12 years ago

Reputation: 271

3Welcome to Code-Golf! Don't forget to add an explanation on why this answer is creative! – Justin – 12 years ago

3@Quincunx It's an easter egg in SWI-Prolog. – svick – 12 years ago

15

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

palerdot

Posted 12 years ago

Reputation: 269

2I’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. – bodo – 12 years ago

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 – 12 years ago

1I don’t mean your conversion of it into an array. I said order. The context makes it obvious that it’s a date. Writing it as [1,9,5,2,0,3,1,1] would make the comment redundant. – bodo – 12 years ago

1Oh ok. I'm from a different time zone (GMT + 5:30). If I have to write it in a format from our timezone it will be [1,1,0,3,1,9,5,2]. I thought this is the way most people understand the date. Anyway, I will change the order – palerdot – 12 years ago

24@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 – 12 years ago

1@palerdot I'm British, and I always write dates as dd/mm/yyyy, not yyyy/mm/dd. – Toothbrush – 12 years ago

7@palerdot. As far as I know, only US-Americans (and occasionally Canadians) write dates in that weird, confusing, "middle-endian" manner. – TRiG – 12 years ago

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.?. – ChiefTwoPencils – 12 years ago

1

Ever heard about ISO 8601? https://xkcd.com/1179/

– Rulle – 12 years ago

15

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?

devnull

Posted 12 years ago

Reputation: 1 591

No ..please explain! – Antonio Ragagnin – 12 years ago

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 – 12 years ago

15

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.

sam hocevar

Posted 12 years ago

Reputation: 581

12

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

Mukul Kumar

Posted 12 years ago

Reputation: 2 585

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. – None – 12 years ago

Cool, once I fixed it. – None – 12 years ago

@user2509848 what was the error ? – Mukul Kumar – 12 years ago

Posted it in the first comment. Visual Studio wanted getch to be _getch instead. – None – 12 years ago

12

JavaScript

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

Outputs 42.

Jonathan

Posted 12 years ago

Reputation: 521

12

Brainf**k

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

Timtech

Posted 12 years ago

Reputation: 12 038

Does this depend on an overflow in the interpreter? – Cruncher – 12 years ago

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 – 12 years ago

@Cruncher It needs 8-bit wrapping cells. This is the most common type. – Timtech – 12 years ago

12

J

Symmetric one-liner without alphanumeric chars.

   _<.>.>_ (=(+^:]) ~=(-*-)=~ ([:^+)=) _<.<.>_

Outputs 42.

The main computation is:

ceiling( 1 + ( 1 - e ^ 2 ) ^ 2 ) = 42

randomra

Posted 12 years ago

Reputation: 19 909

11

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

Huijari

Posted 12 years ago

Reputation: 121

You could also write "The End of the Universe"|0 – Toothbrush – 10 years ago

2

I prefer to think of it as a Kleene Star.

– primo – 12 years ago

10

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

Amal Murali

Posted 12 years ago

Reputation: 237

1Going 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 – 12 years ago

10

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
    

e-sushi

Posted 12 years ago

Reputation: 555

I count 44 bytes. – Doorknob – 12 years ago

@Doorknob Then you should count again... 11 + \n + 15 + \n + 14 = 42 bytes including the two newlines. – e-sushi – 12 years ago

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 – 12 years ago

Hmmm, must have been SE modding my copy-and-paste. Thanks for killing two invisible chars then. ;) – e-sushi – 12 years ago

3Still 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  – 12 years ago

@GlennRanders-Pehrson Nope, that would be 41 chars… unless you put a space between that. I'll add an edit to my answer to show you what I mean. – e-sushi – 12 years ago

Q: How many bytes are there in Glenn's version? A:the answer is 42 according to 'wc'. I guess it was erroneously counting the terminal newline. – Glenn Randers-Pehrson – 12 years ago

@GlennRanders-Pehrson I count that stuff manually just to be sure. ;) Anyway, there wouldn't be a horizontal version without you… thanks for that! – e-sushi – 12 years ago

A valid shell script has a newline at the end. – celtschk – 12 years ago

10

CSS

Here's one I made myself, hand drawn in CSS.

html, body {padding:0; margin:0;}
:before, :after {display:block; content:''; position:absolute;}
html:before {
    border-top:20px solid transparent;
    border-right:14px solid transparent;
    border-bottom:20px solid;
    border-left:24px solid;
    padding:25px; width:35px; height:20px;
    -webkit-transform:skewX(-35deg);
    -ms-transform:skewX(-35deg);
    transform:skewX(-35deg);
    top:10px; left:50px;
}
html:after {
    border-right:20px solid;
    left:88px; top:10px;
    width:0; height:170px;
}
body {
    border:20px solid;
    border-radius:100px;
    padding:42px; width:0; height:0;
    border-bottom-color: transparent;
    border-left-color: transparent;
    position:relative; left:120px; top:9px;
}

body:after {
    border-top:20px solid transparent;
    border-right:20px solid transparent;
    border-bottom:20px solid;
    border-left:28px solid;
    padding:25px; width:15px;
    -webkit-transform:skewX(-45deg);
    -ms-transform:skewX(-45deg);
    transform:skewX(-45deg);
    top:62px; left:37px;
}

Markupless fiddle: http://jsfiddle.net/MrLister/A3f85/1/

Output:

42

Mr Lister

Posted 12 years ago

Reputation: 3 668

10

Piet

42 Piet

After the "Hello World", this is the first thing I tried in Piet, it start in the top left, push 42 ten times to the stack(maybe I'll make a 42 times), add them(the colored part), divides by 10, and outputs(the light blue part at the top of '2').

42 Piet Simple

And this is a very simple 42.

f.rodrigues

Posted 12 years ago

Reputation: 645

This is art in multiple point of views! – bobbel – 10 years ago

8

C#

TimeSpan thoughtTime = new TimeSpan(65221821, 18, 13, 20, 0);
for (int i = 0; i < 42; i++)
{
    Thread.Sleep(thoughtTime);
}
Console.WriteLine("42");

...aaaand seven and a half million years later... voila!

Dylan Cristy

Posted 12 years ago

Reputation: 181

7

C++, Windows (TTS)

Turn your volume up.

#include <sapi.h>

int main () {

    // compute 6 * 9
    int value = 6 * 9;
    wchar_t str[3];
    wsprintf(str, L"%i%i", value/13, value%13);

    // display result
    CoInitializeEx(NULL, COINIT_MULTITHREADED);
    ISpVoice *v;
    CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&v);
    for (int n = 0; n < _wtoi(str); ++ n)
        v->Speak(str, 0, NULL);
    v->Release();
    CoUninitialize();

}

Result is presented 6*9 times. Compile with MSVC. As far as I can see this is the only audio version here.

Jason C

Posted 12 years ago

Reputation: 6 253

7

Ruby

I didn't see a Ruby entry (except the 6*9 one), so here's a stab:

<<z.scan(/\S/).each_slice(8){|b|i=0;(?0+b.map{|h|'%04b'.% '0x'+h}.join).scan(/.../).each{|m|$><<' #'[i%2]*m&&i+=1 if 0!=(m=m.to_i 2)};puts}

    0A   692D
  0C91  4D  74
 D1 03     71
74D191   4D
    74  D1
    0A  69730C
z

(Yes, the big "42" above is part of the program, not the output.)

Output

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

(That's 42 in Roman numerals.)

Notes

I could have golfed this some more but since this wasn't actually a golfing challenge I quit pretty quick. If anyone is interested in an ungolfing I'd be happy to write it up, but there's no particularly interesting magic going on here.

Jordan

Posted 12 years ago

Reputation: 5 001

XLII doesn't sound like the answer to the meaning of life to me. It sounds like the answer to "What size T-shirt is that?" Double extra large. – Level River St – 12 years ago

6

Perl

extrapolation in base 13

#!/usr/bin/perl
BEGIN
{
    eval "use Deep::Thought" or warn "DON'T PANIC\n";

    package Ultimate;

    our $Answer = "Share and Enjoy";

    sub Question
    {
        my ($min, $t, $s, %t) = (2, 13);

        my @cake = map {/[a-z]/i ? -97 + ord lc : ($t{$_} ||= --$t)} split //, shift;

        $s += $_ for @cake;

        $s = ($s * $min) % 13;

        my $v = $cake[0];

        for (my $more = 12; $more--;)
        {
            $v = ($v + 1) % 13;

            $v = $min if $v < $min;

            my @tpv = @cake;

            for (@cake)
            {
                my (@t, @u, @lie);

                @u = @t = @tpv;

                for my $brownian (@t)
                {
                    $brownian *= $s * 13 - $v;
                }

                $t[0] += $min;

                for (my $i = 0; $i < @cake; $i++)
                {
                    print((" " x ($t[$i] % (6 * 9))), ".");

                    $t[$i + 1] += int $t[$i] / 13 if $i + 1 < @cake;

                    $t[$i] %= 13;
                }

                my $zero;

                for (my $i = 0; $i < @cake; $i++)
                {
                    for (my $j = 0; $i + $j < @cake; $j++)
                    {
                        my $ij = $i + $j;

                        $lie[$ij] += $t[$i] * $u[$j];

                        $lie[$ij + 1] += int $lie[$ij] / 13 if $ij + 1 < @cake;

                        $lie[$ij] %= 13;
                    }

                    $zero = 0 if $lie[$i] != $tpv[$i];

                    $tpv[$i] = $lie[$i];
                }

                next if $zero ~~ 0;

                print "\n";

                my @d;

                for (my $i = @tpv; $i--;)
                {
                    $_ *= 13 for @d;

                    $d[0] += $tpv[$i];

                    for (my $j = 0; $j < @d; $j++)
                    {
                        next if $d[$j] < 1000000;

                        $d[$j + 1] += int $d[$j] / 1000000;

                        $d[$j] %= 1000000;
                    }
                }

                our $Answer = "";

                $Answer = sprintf "%06d%s", $_, $Answer for @d;

                return;
            }

            warn sprintf "%s%s\n", ($more ? "DON'T " : ""), "PANIC";
        }

        die "Total Existence Failure\n";
    }
}  

"Life, the Universe, and Everything"->Ultimate::Question;

END
{
    my ($false, $truth);

    while ($Ultimate::Answer =~ /(\d{4}(\d\d))/g)
    {
        ($false, $truth) = ($1, $2);

        $false =~ s/(?<=..)(..)/ $1 /;

        print "$false\n";
    }

    print "\n";

    exit $truth;
}

126 lines. The output?

DON'T PANIC

The Total Perspective Vortex, extrapolated from the array @cake. After some false starts, it eventually produces on a 160-column terminal:

. .                                                 .                                     .                         .                                           
.                         .                         ..                    .                                     .                                               
.                    .                   .  .     .                       .                          .                                    .                     
                                .              .       .                                                  .          .                                          
    .                                         .        .   . .                                                 . .                   .  .                       
         . . .                                                 .                                     .                         .                                
           .                         .                                                 .                                           .                            
   .       .       .             .                   .                                     .                                                 ..                .

...

               .                                                   .     .                   .                                . . .                             
                    .                                     .                         .                                           .                         .     
                                            .                                           .                               .       .       .             .         
          .                                     .                   .                               .       .             .                               . . . 
                                                .                                     .                         .                                           .   
                      .                                                 .                                           .                               .       .   
                                  .                                                .                                . . .                                       
          .                                     .                         .                                           .                         .               
                                  .                                           .                               .       .       .             .                   
.                                     .                   .                               .       .             .                               . . .           
                                      .                                     .                         .                                           .             
            .                                                 .                                           .                               .       .       .     
        .
00 00 54
37 62 45
45 35 54
55 00 23
09 16 88
75 04 85
15 77 42

with an exit status of that last number. Most of the work is done by $brownian motion in @t before line 42.

user130144

Posted 12 years ago

Reputation: 303

6

Befunge

Now, I know I'm fairly late to the show, but I wanted to try something using befunge:

42*2+42+::*\->" "\1-:v>$82+>"2"\1-:v>$" 444"42+:*>" "\1-:v>$442++v              
v  42*42+4242^  $*42 _^4242^$*2*42 _^42 42 42 42 ^  $%42 _^42*42%>
>42+:*>" "\1-:v>$"222  444"42+:*>" "\1-:v>$42*2+42+:*1-v>424<
vchuck^norris _^the question of ^$$life _^the universe >
>>" "\1-:v>$"222 4"42*2+>"4"\1-:v>$42*4*2->" "\1-:v>$442++42*4*v_and everything
v^$!%42  _^    6*9=?    ^     DA_^knows   ^$the   _^answer: 42 >
>" ">" "\1-:v>$"222 "::"  444  444"42*4*>" "\1-:v>$$42+4+v forty-two
  v ^ $$ 42 _^42% 42+ \!:+* 42*- 42\$   ^ $*42  _^       >42      $$
  >42*4*1->" "\1-:v>$"222"42*>" "\1-:v>$$"444 444"424**>" "\1-:v>$42*2+v
  v       ^       _^         ^       _^                ^       _^      >
  >42+:4*+>" "\1-:v>$"222    222 ":::"444"44*2*1+>" "\1-:v>$24:++v
  v       ^       _^                             ^       _^      >
  >" "442**2->" "\1-:v>$42*>"2"\1-:v>$4>" "\1-:v>$"444"244**2+>" "\1-:v>$v
v            ^       _^    ^       _^  ^       _^             ^       _^ >
>004:*p   v>04:*g14:*gp:42*2+-#v_$004:*p144*g1+144*pv                  v
  v p*:410<^              <    >04:*g1+044*p                           v
  >       >^              |       -7g*:41           <                  <
v                         <
>42*42*2+*>" "\1-:v>$>:#v_v
          ^       _^ ^> >  04:*g14:*gp04:*g1+04:*pv
^                    ^         _v#-**44*44g*:40   <>14:*g1+14:*p2044*p
@theonlygusti        >^   >                        ^>
                                >                   ^

Now, this program is special in that it produces no output! None whatsoever! Instead, it modifies its own source to display 42, ASCII-art style.

                                444    22222222
                               444    222    222
                              444 444       222
                             444  444     222
                            44444444444 222
                                  444  222
                                  444 2222222222

Therefore, I recommend Alexios' interpreter to visualize it.

To make it slightly more challenging, I've tried to only use the digits 4 and 2 wherever possible, but have often used a 1 instead of (my alternative) 42%!.

I thought this would be a pretty cool concept, and I love how the program uses its own destruction to end!The program, as its overwritten, reaches some of the code which keeps the loop going, and therefore ends. I'd love to explore this idea further in the future!

One of my other ideas was to have a befunge program generate some brainfuck as its output, and the brainfuck, when run, would generate the befunge which generated it! I might try that later, post as another answer here.

theonlygusti

Posted 12 years ago

Reputation: 1 221

5

Bash

#!/bin/bash
if [ "$1" == "the Ultimate Question of Life, the Universe, and Everything" ]; then
echo 42
fi

produces:

~$ ./Answer "the Ultimate Question of Life, the Universe, and Everything"
42

s3lph

Posted 12 years ago

Reputation: 1 598

3But where is ./Question? – Cole Johnson – 12 years ago

5

HTML 5 + Javascript

<!DOCTYPE html>
<html>
<body>

<canvas id="monalisa" width="200" height="200" style="border:1px solid #000000;">
Your browser is non-artistic !! 
</canvas>

</body>
<script>
    var question = "Answer to life the universe and everything";
    var c = document.getElementById("monalisa");
    var context = c.getContext("2d");
    context.fillStyle = "rgb(255, 0, 0)";
    var text = question.length;
    context.font = "180px Arial";
    context.strokeText(text, 1, 160);
</script>
</html>

Output:

Canvas

Demo:

http://jsfiddle.net/NmHty/1/

Ashwin

Posted 12 years ago

Reputation: 151

5

Binary:

00000000011000000011111000
00000001111000001100000110
00000110011000011000000011
00011000011000000000000110
01100000011000000000011000
11111111111111000001100000
00000000011000001100000000
00000000011000011111111111

Dozer789

Posted 12 years ago

Reputation: 281

@MatthewWilcoxson How? – theonlygusti – 10 years ago

5This is a programming contest, not an arranging-the-characters contest. – user12205 – 12 years ago

4@ace And binary is a programming language. :) – Dozer789 – 12 years ago

1Technically it's the ONLY programming language ;) – Matthew Wilcoxson – 12 years ago

4

Javascript

var x = console.log;

x('    ' +4 + '    ' + 2,2,2);
x('  ' + 4 + ' ' + 4 + '   ' + 2 + '   ' + 2);
x(' ' + 4 + '  ' + 4 + '      ' + 2);
x(4+' '+ 4+' '+ 4+  '     ' +2);
x('    ' + 4 + '   ' + 2);
x('    ' + 4 + '  ' + 2,2,2,2);

Output

    4    2 2 2
  4 4   2   2
 4  4      2
4 4 4     2
    4   2
    4  2 2 2 2

user12183

Posted 12 years ago

Reputation:

People not like my answer? I'm new, please let me know why I get no upvotes? – None – 12 years ago

1Sorry. I didn't see it earlier. – Toothbrush – 12 years ago

4

C

#include <stdio.h>
const int YEAR_OF_PRODUCTION = 1979;

int main(int argc, char** argv) {
        char* name = argv[0];
        char c;
        int i = 0;
        while((c = *(name++)) != 0) {
                i += c*2;
        }
        printf("%d\n",2*(i-(YEAR_OF_PRODUCTION + 6)));

        return 0;
}

Compile as an executable named "fortytwo" and run in the same directory on a linux system as in:

./fortytwo

Result:

42

user17134

Posted 12 years ago

Reputation: 41

4

Java

This one's another one using Strings. :)
Here, I use the letters inside the title of the book to create it, while using variable names related to the book, itself.
Don't forget to include/import your library classes before executing!

String towel = "The Hitchhiker's Guide to the Galaxy";
char babel = towel.charAt(32);
char heart_of_gold = towel.charAt(34);
char harmless = towel.charAt(5);

babel = Character.toUpperCase(babel);
heart_of_gold = Character.toUpperCase(heart_of_gold);
harmless = Character.toUpperCase(harmless);

System.out.println(heart_of_gold + babel + harmless + harmless);

Output should be:

XLII

...which is Roman-Numeral for 42. :)

mikhailcazi

Posted 12 years ago

Reputation: 779

1Can you please add the public class ClassName { public static void main(String[] args) { { ... } }? This way this answer would be complete. – Victor Stafusa – 12 years ago

@Victor This is a popularity-contest, not code-golf. The class declaration should be obvious to anyone who knows Java. – IQAndreas – 12 years ago

@IQAndreas But not everybody knows java, and without these, the program is untstable. – Victor Stafusa – 12 years ago

1@Victor Someone who doesn't know Java isn't going to test the code anyway. ;) (they likely won't even have the compiler installed on their computer). – IQAndreas – 12 years ago

4

Rebol

letters: charset [#"a" - #"z"]
nothing: 0
words: []

parse "the meaning of life" [
    any [
        copy word some letters (append words word) |
        space (++ nothing)
    ] (
        deep-thought: sort map-each n words [length? n]
        print (first deep-thought) * nothing * (last deep-thought)
      )
]


Output:

42

draegtun

Posted 12 years ago

Reputation: 1 592

What the...:-) nice one. – TheBlastOne – 12 years ago

4

PHP – 134 bytes

Description:

On 3 November 1993, he gave an answer at alt.fan.douglas-adams about the origin of “42”:

I sat at my desk, stared into the garden and thought “42 will do”. I typed it out. End of story.

Based on that answer, this should be the way Douglas Adams would have commented his PHP code…

Source:

<?php 
/* The Ultimate Answer to Life, The Universe and Everything is… */ echo(42);
/* So Long, and Thanks for All the Fish. */ exit();

The comments represent quotes by Douglas Adams, but they also fit/describe the PHP functionalities.

e-sushi

Posted 12 years ago

Reputation: 555

2+1 nice one! Even though Adams wouldn't forget a ?> at the end ;) – bobbel – 12 years ago

3@bobbel [+1] on your comment. While I would like to note that the trailing ?> isn't needed in PHP, I guess you're right in the sense that Adams died before the closing ?> was deprecated. – e-sushi – 12 years ago

4

C one-liner

c(x,y){return(y<x?0:x?c(x-1,y)+c(x,y-1):1);}main(){printf("%d\n",c(5,5));}

The appearance of the magic number 5 is, of course, a reference to the number of books in the Hitchhiker's Trilogy.

Spoiler:

Computes the 5th Catalan number.

Nate Eldredge

Posted 12 years ago

Reputation: 2 544

4

JavaScript and string theory

Refactored from my other answer: Write a mathematical function whose result is "hello world"

function stringTheory(theory) {
  var proof = 0;
  var principles = theory.split(/[ ,.'-]/);
  for (var i = 0; i < principles.length; i++) {
      var formula = '';
      for (var j = 0; j < principles[i].length; j++) {
        formula += principles[i].charCodeAt(j).toString(10);
      }
      proof += +formula;
  }
  return proof;
}

console.log(
     stringTheory("Hello world")
-
     stringTheory('\2 Yo it\'s 4327 - Go to space, look back, and see the dot of a small blue rock you once sat on amid the vast empty void - KA-BOOM - you are in awe of it. "Ah" - so tiny in this vast space yet you are even more so. A mere atom in an ocean of stars, the earth a speck of dust to the sun\'s ping-pong ball. One day you shall go back and as your toes touch the soft soil once more, the cool wind in your hair as you cast your gaze upon the moon, a mere rock just like this one, and bask in it\'s warm glow - Ah. Only then can you know the scale of it all, what luck you have to call this place home.  And with this new ken, a love you\'ve kept for all of time but had not seen - for it is clear to you now. You lay open your arms and fill the air with your song - (aah) ~o Good-bye space and ... o? \3')
);

What is going on?

Using stringTheory() we subtract Hello world from '\2 Yo it\'s 4327 - Go to space, look back, and see the dot of a small blue rock you once sat on amid the vast empty void - KA-BOOM - you are in awe of it. "Ah" - so tiny in this vast space yet you are even more so. A mere atom in an ocean of stars, the earth a speck of dust to the sun\'s ping-pong ball. One day you shall go back and as your toes touch the soft soil once more, the cool wind in your hair as you cast your gaze upon the moon, a mere rock just like this one, and bask in it\'s warm glow - Ah. Only then can you know the scale of it all, what luck you have to call this place home. And with this new ken, a love you\'ve kept for all of time but had not seen - for it is clear to you now. You lay open your arms and fill the air with your song - (aah) ~o Good-bye space and ... o? \3'

and we get 42.

This is equivalent to:

191212222216211 - (2 + 89111 + 105116 + 115 + 52515055 + 71111 + 116111 + 1151129799101 + 108111111107 + 989799107 + 97110100 + 115101101 + 116104101 + 100111116 + 111102 + 97 + 11510997108108 + 98108117101 + 11411199107 + 121111117 + 11111099101 + 11597116 + 111110 + 97109105100 + 116104101 + 11897115116 + 101109112116121 + 118111105100 + 7565 + 66797977 + 121111117 + 97114101 + 105110 + 97119101 + 111102 + 105116 + 346510434 + 115111 + 116105110121 + 105110 + 116104105115 + 11897115116 + 1151129799101 + 121101116 + 121111117 + 97114101 + 101118101110 + 109111114101 + 115111 + 65 + 109101114101 + 97116111109 + 105110 + 97110 + 1119910197110 + 111102 + 11511697114115 + 116104101 + 10197114116104 + 97 + 11511210199107 + 111102 + 100117115116 + 116111 + 116104101 + 115117110 + 115 + 112105110103 + 112111110103 + 9897108108 + 79110101 + 10097121 + 121111117 + 11510497108108 + 103111 + 989799107 + 97110100 + 97115 + 121111117114 + 116111101115 + 11611111799104 + 116104101 + 115111102116 + 115111105108 + 11111099101 + 109111114101 + 116104101 + 99111111108 + 119105110100 + 105110 + 121111117114 + 10497105114 + 97115 + 121111117 + 9997115116 + 121111117114 + 10397122101 + 117112111110 + 116104101 + 109111111110 + 97 + 109101114101 + 11411199107 + 106117115116 + 108105107101 + 116104105115 + 111110101 + 97110100 + 9897115107 + 105110 + 105116 + 115 + 11997114109 + 103108111119 + 65104 + 79110108121 + 116104101110 + 9997110 + 121111117 + 107110111119 + 116104101 + 1159997108101 + 111102 + 105116 + 97108108 + 11910497116 + 10811799107 + 121111117 + 10497118101 + 116111 + 9997108108 + 116104105115 + 1121089799101 + 104111109101 + 65110100 + 119105116104 + 116104105115 + 110101119 + 107101110 + 97 + 108111118101 + 121111117 + 118101 + 107101112116 + 102111114 + 97108108 + 111102 + 116105109101 + 98117116 + 10497100 + 110111116 + 115101101110 + 102111114 + 105116 + 105115 + 9910810197114 + 116111 + 121111117 + 110111119 + 89111117 + 10897121 + 111112101110 + 121111117114 + 97114109115 + 97110100 + 102105108108 + 116104101 + 97105114 + 119105116104 + 121111117114 + 115111110103 + 40979710441 + 126111 + 71111111100 + 98121101 + 1151129799101 + 97110100 + 11163 + 3)

George Reith

Posted 12 years ago

Reputation: 2 424

4

Bash, coreutils

It seems appropriate that the manpage for random has the number 42 built in:

$ man random | head -n 1 | tr -d " " | wc -c
42
$ 

As does the above command itself:

$ s='man random | head -n 1 | tr -d " " | wc -c'
$ echo ${#s}
42
$

Digital Trauma

Posted 12 years ago

Reputation: 64 644

4

PowerShell

Write '42' to a bitmap, then use the pixel data to write ASCII art '42'

$null = [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$bmp = New-Object System.Drawing.Bitmap(24, 20)
$font = New-Object Drawing.Font 'Courier Regular',20,0,2
$graphic = [drawing.graphics]::FromImage($bmp)
$graphic.DrawString(42, $font,[drawing.brushes]::White, 0, 0)

$rect = new-object drawing.Rectangle (0, 0, $bmp.Width, $bmp.Height)
[Drawing.Imaging.BitmapData]$bd = $bmp.LockBits($rect,
        [Drawing.Imaging.ImageLockMode]::ReadOnly, 
        [Drawing.Imaging.PixelFormat]::Format1bppIndexed)

$bp = New-Object Drawing.Bitmap (24, 20, $bd.Stride, 
        [Drawing.Imaging.PixelFormat]::Format1bppIndexed, 
        $bd.Scan0)

foreach($y in 0..19) {
    foreach($x in 0..23) {
        if($bp.GetPixel($x, $y).r) { $p = '42' }
        else { $p = '  ' }
        Write-Host $p -NoNewline
    }
    Write-Host
}

The output:

              4242            4242424242    
              4242          42424242424242  
            424242        424242      424242
          42424242        4242          4242
        4242  4242                      4242
        4242  4242                      4242
      4242    4242                      4242
    4242      4242                    4242  
    42        4242                  4242    
  42424242424242424242            4242      
  42424242424242424242        424242        
              4242          4242            
              4242        424242            
              4242        424242424242424242
              4242        424242424242424242

Rynant

Posted 12 years ago

Reputation: 2 353

4

Perl

am I creative enough?

print eval join ~ P & k, map length of x length, Just, another, Perl, hacker

Edit: Explanation

length of x length is a creative way to write 2 * length as it evaluates to length('of' x length($_)).

~ P & k is not a probability calculation but just a way to get a plus sign (ab)using barewords.

So in clean code, this is more or less:

print eval join '+', map 2 * length, qw/Just another Perl hacker/

chinese perl goth

Posted 12 years ago

Reputation: 1 089

2I don't know, but +1 because your username is awesome. – Jason C – 12 years ago

4

Java

42 happens to be the number of full binary trees with six leaves.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FortyTwo {

    private static class TreeNode {
        TreeNode left;
        TreeNode right;
    }

    private static List<TreeNode> fullTreesWithNLeaves(int n) {
        if (n == 1) {
            return Arrays.asList(new TreeNode());
        } else {
            List<TreeNode> result = new ArrayList<TreeNode>();
            for (int leftLeaves = 1; leftLeaves < n; leftLeaves++) {
                int rightLeaves = n - leftLeaves;
                List<TreeNode> leftTrees = fullTreesWithNLeaves(leftLeaves);
                List<TreeNode> rightTrees = fullTreesWithNLeaves(rightLeaves);
                for (TreeNode left : leftTrees) {
                    for (TreeNode right : rightTrees) {
                        TreeNode root = new TreeNode();
                        root.left = left;
                        root.right = right;
                        result.add(root);
                    }
                }
            }
            return result;
        }
    }


    public static void main(String[] args) {
        System.out.println(fullTreesWithNLeaves(6).size());
    }

}

Joe K

Posted 12 years ago

Reputation: 1 065

4

CharPlot

Plotting with Chars. You can do it with 42 and with your girl friend, too.

public class CharPlotUtil {

    private static int xStep = 2;
    private static int yStep = 2;

    public static void main(String[] args) throws IOException {

        initChars(" .:0123456789oO*+-,;dc3öÖ%qQG´");

        BufferedImage bufferedImage = ImageIO.read(new File("D:\\Temp\\Chars\\img.png"));
        // http://www.stupidedia.org/images/8/80/The_Answer_to_Life,_the_Universe,_and_Everything.png

        int normalizationFactor = 3 * xStep * yStep * 255;

        for (int y = 0; y < bufferedImage.getHeight() - yStep; y += yStep) {
            for (int x = 0; x < bufferedImage.getWidth() - xStep; x += xStep) {

                int sum = 0;
                for (int xx = x; xx < x + xStep; xx++) {
                    for (int yy = y; yy < y + yStep; yy++) {
                        int value = bufferedImage.getRGB(xx, yy);
                        int byte1 = value & 0xFF;
                        int byte2 = (value >> 8) & 0xFF;
                        int byte3 = (value >> 16) & 0xFF;
                        sum += byte1 + byte2 + byte3;
                    }
                }
                float f = ((float) sum) / normalizationFactor;
                System.out.print(CharWithGrayValue.getCharByGrayValue(f).getChar());
            }
            System.out.println();
        }
    }

    private static void initChars(String charsAsString) {

        for (int i = 0; i < charsAsString.length(); i++) {
            char c = charsAsString.charAt(i);
            CharWithGrayValue.add(new CharWithGrayValue(c));
        }
    }
}

public class CharWithGrayValue {

    private static int width = 16;
    private static int height = 24;
    private static int fontSize = 23;
    private static Font font = new Font("Courier New", Font.PLAIN, fontSize);

    private static Map<Integer, CharWithGrayValue> charsWithGrayValue = new TreeMap<>();
    private static int minGrayValue = -1;
    private static int maxGrayValue = 0;

    private char c;
    private int grayValue;

    public CharWithGrayValue(char c) {
        this.c = c;
        grayValue = getGrayValue(c);
    }

    public char getChar() {
        return c;
    }

    public int getGrayValue() {
        return grayValue;
    }

    private static int getGrayValue(char c) {

        BufferedImage charImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        Graphics graphics = charImage.createGraphics();
        graphics.setFont(font);
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.BLACK);
        graphics.drawString("" + c, 0, height - 4);
        return getGrayValue(charImage);
    }

    private static int getGrayValue(BufferedImage charImage) {
        int result = 0;
        for (int i = 0; i < charImage.getHeight(); i++) {
            for (int j = 0; j < charImage.getWidth(); j++) {
                if (charImage.getRGB(j, i) != -1) {
                    result++;
                }
            }
        }
        return result;
    }

    public static void add(CharWithGrayValue cg) {
        charsWithGrayValue.put(cg.getGrayValue(), cg);
        if (cg.getGrayValue() > maxGrayValue) {
            maxGrayValue = cg.getGrayValue();
        }
        if (cg.getGrayValue() < minGrayValue || minGrayValue == -1) {
            minGrayValue = cg.getGrayValue();
        }
    }

    public static CharWithGrayValue getCharByGrayValue(float normalizedGrayValue) {

        // normalizedGrayValue: 0, ..., 1
        // intGrayValue: minGrayValue, ..., maxGrayValue

        int intGrayValue = (int) (minGrayValue + (maxGrayValue - minGrayValue) * normalizedGrayValue);
        for (int gv : charsWithGrayValue.keySet()) {
            if (gv >= intGrayValue) {
                return charsWithGrayValue.get(gv);
            }
        }
        return new CharWithGrayValue(' '); // Should not happen
    }
}

                                                                                                                     ´´´´´                                      
                                              ,c7co333oc777cooooooo,                                       ´.,:*7c7;;:::::::::::,-..                            
                                             .3occo3223occccooo3ooo,                                   ´,*o3o3333o7;:::::::::*;;;;;;;:,.´                       
                                            .223occo3223oooooo33333,                                 .;555233322o7;*:::::::*;;;;;;77;;;;:,.                     
                                           ´o55233oo32523ooooo33333,                               .o55455232223c7;*::::::*;;;77777;;;;*::::.                   
                                           72555523o325523oooo33222:                             ´;255445222252o7;**::::*;;77777777;;;*:::::::´                 
                                          :325554523o32552333332222:                            ,o2554ö45225523c;;**::*;;777777777;***:::::::::-                
                                         .7o32554452332555233332222:                          ´:o2554öö5555553o7;;***;;7777cccc77;;;**:******:;;:´              
                                        .*;7o3554öö4523254522222222:                         ´73325ö664555552o7;;;**;;7cccccoc77;;;****;;;;;;;77;*´             
                                       ´;;;;7o254öö6452254452222255:                        ´73325ö68ö4554453c7;;;;;7cooooooo77;;;;;;;;**;;;;77777;´            
                                      ´;77;;;7o254ö6645225ö45222255:                        72325ö688ö554ö53o77;;;77ooooooooc7;;;;;;;;;;;;777777c77;´           
                                      *oc777;;7o24ö688ö525464522255:                       :522546886444ö42oc77;77co333333oc77;;;;;;;;777777ccoccccc:           
                                     :33ooc7777c3246888ö555ö6455555:                      .5522468G8ö4ö6ö53c7777co3333333oc77;;;;;;;7777cccooooocc777-          
                                    ,22233oooc77c35ö688865548845555:                      2552568GG8öö6653oc777o33222223oo7777777777cccooooooooccccc7;´         
                                   .322552233ooc7o35ö88GG6456884555:                     :4555ö8GG86688423occoo32222223oo77777777ccoooo333ooooooccc7;7:         
                                  ´7o3225552233oooo3568GGG84ö8G8454:                    ´5ö5548GGG8888ö23oooo322555523oocccccccoooo33333333ooooocc77;;;´        
                                 ´;cco325544552233oo256GG%G8ö6GG844:                    :6ö558G%%G88G6533oo32255555233ooooooooo333222223333ooooc777;*;;,        
                                 :77coo3255öö45522333258G%%G8ö8GG6ö:                    28ö56G%%G8GG8523333255544553:.´´´´.:o32225522223333oooc77;;*;;**        
                                ,777ccoo3255ö664552223258G%q%86GGG6:                   .88öö8Gq%GGGGö2333255444452:´        ´:555555222333ooc77;;;;;;*;;.       
                               .;;77ccoo332254686ö45223248%%q%G8G%G:                   *88ö8GqqGGGG65233254öööö52.            -5455522233occ777;;;;*::::,       
                              ´*;;777cooo3322546886ö452224G%qq%GG%%*                   5886Gqq%G%%8522254ö666ö52.              .5555223ooc77;;;;;***:::;:       
                             ´:*;;;777coo332225468G88ö45224GqqqqGG%;                  ´G888%qq%%%G45225ö6888ö55:                :55233oo777;;;;;**::::*::´      
                            ´::**;;;777coo332255468GGG8ö455öGqqQqG%;                  :G88%qQq%qG65254888G8ö453                 ´323ooc77;;;;;;*****:;*::.      
                            ,:::**;;;77cco33222554ö8G%GG8ö45öGqQQqG;                  7G8GqQqqq%845568GGG86455,                  :ooc777;;;;;****::::*:::.      
                           .:::::*;;;;77coo33225554ö8G%%GG864öGqQQq*                  4G8qQQqqq8ö548GGGG8644ö4´                  .oc777;;;;;****:::::::::.      
                          .::::::**;;;777coo33225554ö8G%qqGG866GQQQ;                  GG%QQQqqG6ö68GG%G86ö668o                   ´c777;;;;;****::::::::::.      
                         ´:::::::**;;;;777coo3322554ö68GGqqqGG88GQQ7                 .%GQQQQQG868G%%%G88888GG:                    777;;;;;;****::::::::::.      
                        ´:::::::***;;;;777ccoo.322554ö68GG%qqqG88GQ7                 :GqQQQQ%868Gqq%G88GGG%qq.                   ´777;;;;;;***::*::::::::.      
                        :;;********;;;;7777co, 3322554ö88GG%qQq%G8G;                 ;%QQQQq88G%qq%GGGGGqqQQq                    .77;;;;;****:**::::;**::.      
                       :777;;;;;;;;;;;;7777c:  33322554ö88GG%qQQq%G*                 ´´´´´´´´´´´´´´´´´´´´´´´´                    ,77;;;;;;*****::::::::::´      
                      ,7777ccccccc77777777c*   333222554ö88GGGqQQQq;                                                             ;77;;;;;;***::::::::::::       
                     .7777ccoooooooooooooo7´   3333222554ö88GG%qQQQ7                                                            .77;;;;**::::::::::::::::       
                    ´;7777ccoooo3333222223.    33332222554ö88GG%qqQ7                                                            ;7;;;;**::::::::::::::::.       
                   ´*77777ccoooo333322255.     555222225554ö888G%qq7                                                           ,;;;;**::::::::::::::::::.       
                   :;;;;7777cooo33332255:      6666öö445544ö6888GGq;                                                          .;;;;**:::::::::::::::::::        
                  ,***;;;;7777cooo33322*       6888GGGGG8888888888G*                                                         ´;;;;;;***::::::::::::::::-        
                 .:::****;;;;777ccooo3;        6688GGGGG%%%%%GG8888*                                                        ´*77;;;;;;***::::::::::::::´        
                .::::::::***;;;;777co7´        44ö688GGG%%qqqqQQQqq;                                                       ´;77777;;;;;;;;*****;*:*:::,         
               ´:::::::::::::**;;;;77´         25554ö688GGG%qqqQQQQ7                                                      ´73ooooocccc7777777;7;;77;;;´         
              ´,:::::::::::::::::**;.          332225554ö6888GGG%qQ7                                                     .2555522223333ooooooccc7c777:          
              ,::::::::::::::::::::.           ooo33332225554ö66688:                                                    ,688866ööö4455522223333ooooo7´          
             -:::::::::::::::::***,            2222554ö6888GG%qqqQQ7                                                   :44445555522223333ooooocccc77.           
            .:::::::::::**;;;;777:             688GGGG%%qqqqqqqqqQQ7                                                  :333ooooooccc77777777;;;;;;;;,            
           .::::*;;;;;;7777cooo37´             888888GGGGGG%qqQQQQQ7                                                ´;cc777;;;;;*****::::::::::::::             
          ´:;;;77777cccoooooo33o´              444ö688G%qQQQQQQQq%G*                                               .3233ooc777;;;**:::::::::::::::´             
         ´:;7777777777777ccccoo.               68GG%qQQQQQQqGG88GGG*                                              :445552233ooc777;;;**::::::::::´              
         :;77;;;;;;;;;;;777777-                %qqqQqq%G8666888GG8G*                                            ´c4455555222233oocc77;;;;***::::´               
        ,:********;;;;;;;;;77,                 %GG86ö5555ö68888888G;                                           .3555555522223333ooooc7777;;;;*:.                
       .:**:::::*****;;;777c*                  552222554ö6666688GqQ7                                          ,o333332222223333oooocc777777;;;.                 
      ´:::::::***;;;;77coo37´                  333225554444ö688qQQq;                                         *233oocccoooooooooooocc777777;;*´                  
     ´:::::*;;;;;777coo3323´                   322255555554ö8%QQq%q7                                       ´3455233oc77777777777777777777;;:´                   
    ´:****;77777cooo332255.                    222222225556GqQqGGqq;                                      .ö86ö455233oc7;;;*;;;;;;;;;;;;;;:´                    
    ,;;;;7777cooo3333333o-                     333332225öGqQqGG%q%G;                                     ,qq%86ö4552233oc7;;*::::::::****,                      
    ,;;777ccoooooooocc77*--.......---,,,,,,,,,,333322248%qqG8G%qGGQö7**77;;77;                          :8qQQqG8ö4552223oo77;;*:::::::::.                       
    :77ccccc777777;;;;**:::::::**;;;7777ccccoooo333256GqqG88G%%8GQQQq8QQQqQQQq                         *5548%qqqG8ö552233ooc77;;*:::::,´                        
    :77777;;;;;;**::::::::::::**;;;;77777777cooo33248%%G8ö8G%G8GQQQq6qQQ%qQQ%q                        cö552256Gqq%G8452233oooc77;;*::-                          
    ,;;;;***:::::::::::::::::**;;;;;;;;77777coo3258G%G8öö8GG86GQQQq6GQQqGQQQGq                      ´3G8ö552225ö8%qG8645233oocc77;;:.                           
    ,:::::::::::::::::::::::****;;;;;;;;7777co25ö8GG645ö8GG6öGQQQqö8QQQG%QQqGq                     ´2GG884522333248G%G8ö4523oocc77:´                            
    ,::::::::::::::::::::::::::*****;;;;777c3248G86455ö8G844GQQQ%ööqQQ%GqQQGGq                    ´6qG8886452233o3256GGG8ö523ooc7-                              
    -:::::::::::::::::::::::::::::**;;;;77o25ö88ö5525ö88ö54GqQQ%ö5GQQqGGQQqGGq                   ´2%qqG8666452233ooo25ö8G864523;´                               
    -:::::::::::::::::::::::::::::**;;;7o32466ö55225ö8ö554GqQq%628qQqG8GQQ%8G%                  ´4G8GqqG6ööö45223ooc7o324688ö4*´                                
    -:::::::::::::::::::::::::::::**;;7o25ö64522225öö4524Gqqq%ö2ö%qQG8GqQqG8GG                 ´2q%86GqqG644445233oc777c325öö,                                  
    -:::::::::::::::::::::::::::::*;7o324ö45233325445224GqqqGö25Gqqq88GqQ%88GG                 3GGqG6öGq%Gö4555523ooc77;;7oc.                                   
    -::::::::::::::::::::::::::::;;co3545523oo3254522248qqqGö228qqqG68GQqG68G8                7qG8G%Gö48%%8ö5555523oc777;;:´                                    
    -::::::::::::::::::::::::::*;7o3255233oco3255523258qq%Gö23ö%qqG668qQ%8ö8G8               :G%G88G%8448G%8ö5555223oc77;,                                      
    -::::::::::::::::::::::::*;77o32223oo7co325523o358%%%Gö235G%q%846GqqG648G8              .ö8G%G68GG8556GG845222223oc7,                                       
    -:::::::::::::::::::::::*;7c32233oc77co32523oo358%%GG42o28%%%8448%q%8ö4886             ´24ö8GG8ö8GGö55öGG84522223oo,                                        
    -:::::::::::::::::::::*;77o333ooc777co3223ooc358GGG842o3öG%%Gö5ö8qqG65488ö             ;454ö8GG6ö8G8425ö8G64233333,                                         
    -:::::::::::::::::::*;;7co3ooc77;;7co333oocc358GG8842o358G%G655öGq%8ö5486ö            -45555ö8G8448G65224886523337,,,,,--.........--,,,,,,,,,,---.....      
    -:::::::::::::::::**;77ooooc77;;;7co33ooc7c356888842co26GGG85556GqG652ö8ö4           ´5455555688ö5468ö522568ö523oooooc77;;*::::::::*;77coooo7777;;***:      
    .::::::::::::::::*;;7coocc7;;*;;77ooooc777356888653c7348GG842548%%8ö52ö644           *645555556864546842325ö8ö52ooooooc7;;**:::::::::*;;77cooc77;;;;::      
    .:::::::::::::::;;77ccc77;;**;;77oooc77;735ö886653c7o588G8ö2254GqG6525öö55          ´86ö552255468ö5546652o35ö6ö53oocccc77;;**::::::::::*;;777oc777;;;;      
                                               66öö537;c2ö888ö5225ö*                    7G8ö552222548645546ö53o3246453occc7777;;**::::::::::::*;;777777;;;      
                                               öö4537;7356886522258*                   ´8G8ö52222225ö6ö5254ö423o325ö423o7777777;;*::::::::::::::**;;7cc77;      
                                               44537;;o5ö6864232248;                   ;888ö522222225öö52255ö52oco354523o777777;;;**::::::::::::::*;;;7777      
                                               52o7;;c24ö66423325öG*                  ´4888ö5522333225ö452325453o7o32452oc7777;;;;;*:::::::::::::::::*;;;7      
                                               2o7**7354ö6ö53o3256G:                  ,ö688ö55233333355ö523325523c7o32553oc7;;;;;;;***:::::::::::::::::**;      
                                               o7*:;o244öö53oo3258G:                  34ö66ö552333o33254453o32553o77co3523o77;;;;;;;**::::::::::::::::::::      
                                               7*:;73544ö52ooo32488:                 .544ö6ö55233oooo3254523o32523o7;7o3223o77;;;;;*;;::::::::::::::::::::      
                                               *::7o254452ocoo35ö8ö:                 :554ö6ö5523oooooo325523oo3222oc;;7o3223o7;;;**;;;**::::::::::::::::::      
                                               ::;c3555423ccoo25684:                 o5554öö5523oooccoo32553oco3323o7;;7co33oc7;;**;;;;;***:::::::::::::::      
                                               :*73255553o7coo248ö5:                ´255554ö5223ooccccco32523oco3323c7;;7co33oc7;*;*;**:::::::::::::::::::      
                                               :;o222553o77co35ö642:                -25555445223occ777cco3223oc7oo33o7;;;;7oo3o77;;**::;;***::::::::::::::      
                                               ;7322253o777co35öö53,                :22225545233occ77777co323oc77co33o7;**;7coocc7;*:******:::::::::::::::      
                                               7o32222oc;77co25ö523,                ;32222555233oc7777777co323o777coooc7;**;77ooo77;;*::::::::::::::::::::      
                                               c33322oc7;77co24453o,                o32222555233oc77777777co33oc777co3oc7;**;7ccoc7;;**:::::::::::::::::::      
                                               o33323c7;;77c324523c,               ´oo333225523ooc777;;;;77co3oo7;;7cooc7;;:*;77coc7;;*:::::::::::::::::::      
                                               o3333o7;;;77o35423o7,               .co333322523ooc77;;;;;;77co3oc7;;77coc7;*:*;;7cc77;;**:::::::::::::::::      

This is the source image:

42

Frank Henningsen

Posted 12 years ago

Reputation: 41

4

XAML

I really love challenges like this one, as they give you a bit of freedom to experiment. In this case I discovered that Inkscape (a cool free vector graphic application on the PC) can be used to generate XAML. Which for me is awesome and something I never knew before this challenge!

First, I used Inkscape to create a nice colourful vector image or the number 42 (not very exciting as I'm no graphic designer). I then chose to "Save As" and selected "Microsoft XAML (*.xaml)" as the file type.

The vector image of 42 within Inkscape

The output from this is then easily copied into a XAML file within a WPF project.

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Stretch="Uniform">
        <Canvas Name="svg2" Width="346" Height="250">
            <Canvas.Resources>
                <LinearGradientBrush xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Key="linearGradient3762" MappingMode="RelativeToBoundingBox" StartPoint="0,0" EndPoint="1,1">
                    <LinearGradientBrush.GradientStops>
                        <GradientStopCollection>
                            <GradientStop Color="#FFFF0000" Offset="0"/>
                            <GradientStop Color="#FFFFFF00" Offset="0.18175817"/>
                            <GradientStop Color="#FF00FF00" Offset="0.42157799"/>
                            <GradientStop Color="#FF00FFFF" Offset="0.48468846"/>
                            <GradientStop Color="#FF0000FF" Offset="0.73672789"/>
                            <GradientStop Color="#FFFF00FF" Offset="0.8971166"/>
                            <GradientStop Color="#FFFF00FF" Offset="1"/>
                        </GradientStopCollection>
                    </LinearGradientBrush.GradientStops>
                </LinearGradientBrush>
                <LinearGradientBrush xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Key="linearGradient3768" MappingMode="Absolute" StartPoint="106,248" EndPoint="282,248">
                    <LinearGradientBrush.GradientStops>
                        <GradientStopCollection>
                            <GradientStop Color="#FFFF0000" Offset="0"/>
                            <GradientStop Color="#FFFFFF00" Offset="0.18175817"/>
                            <GradientStop Color="#FF00FF00" Offset="0.42157799"/>
                            <GradientStop Color="#FF00FFFF" Offset="0.48468846"/>
                            <GradientStop Color="#FF0000FF" Offset="0.73672789"/>
                            <GradientStop Color="#FFFF00FF" Offset="0.8971166"/>
                            <GradientStop Color="#FFFF00FF" Offset="1"/>
                        </GradientStopCollection>
                    </LinearGradientBrush.GradientStops>
                </LinearGradientBrush>
                <LinearGradientBrush xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Key="linearGradient3780" MappingMode="Absolute" StartPoint="106,248" EndPoint="282,248">
                    <LinearGradientBrush.GradientStops>
                        <GradientStopCollection>
                            <GradientStop Color="#FFFF0000" Offset="0"/>
                            <GradientStop Color="#FFFFFF00" Offset="0.18175817"/>
                            <GradientStop Color="#FF00FF00" Offset="0.42157799"/>
                            <GradientStop Color="#FF00FFFF" Offset="0.48468846"/>
                            <GradientStop Color="#FF0000FF" Offset="0.73672789"/>
                            <GradientStop Color="#FFFF00FF" Offset="0.8971166"/>
                            <GradientStop Color="#FFFF00FF" Offset="1"/>
                        </GradientStopCollection>
                    </LinearGradientBrush.GradientStops>
                </LinearGradientBrush>
                <LinearGradientBrush xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Key="linearGradient3782" MappingMode="Absolute" StartPoint="106,248" EndPoint="282,248">
                    <LinearGradientBrush.GradientStops>
                        <GradientStopCollection>
                            <GradientStop Color="#FFFF0000" Offset="0"/>
                            <GradientStop Color="#FFFFFF00" Offset="0.18175817"/>
                            <GradientStop Color="#FF00FF00" Offset="0.42157799"/>
                            <GradientStop Color="#FF00FFFF" Offset="0.48468846"/>
                            <GradientStop Color="#FF0000FF" Offset="0.73672789"/>
                            <GradientStop Color="#FFFF00FF" Offset="0.8971166"/>
                            <GradientStop Color="#FFFF00FF" Offset="1"/>
                        </GradientStopCollection>
                    </LinearGradientBrush.GradientStops>
                </LinearGradientBrush>
            </Canvas.Resources>
            <!--Unknown tag: sodipodi:namedview-->
            <!--Unknown tag: metadata-->
            <Canvas Name="layer1">
                <Canvas Name="text2985" Opacity="1">
                    <Canvas.RenderTransform>
                        <MatrixTransform Matrix="1.9031797 0 0 2.3496285 -195.43459 -460.36446"/>
                    </Canvas.RenderTransform>
                    <Path xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="path2990" Fill="{StaticResource linearGradient3780}" StrokeThickness="4" Stroke="#FF000000" StrokeMiterLimit="4">
                        <Path.Data>
                            <PathGeometry Figures="m 144.81139 296.64789 c 0.42183 -4.17187 0.79683 -8.60156 1.125 -13.28906 0.32808 -4.68749 0.56245 -8.41405 0.70312 -11.17969 l -7.66406 0.0703 -5.76563 0 -26.4375 0.42188 0.21094 -2.17969 c 0.0469 -0.5156 0.11718 -2.03904 0.21094 -4.57031 l 0.5625 -13.35938 c 0.0469 -1.2187 0.0703 -2.50777 0.0703 -3.86719 4.78124 -5.76557 10.30077 -12.94915 16.55859 -21.55078 6.25779 -8.60148 12.22263 -17.42569 17.89454 -26.47265 7.2187 0.0938 13.71088 0.14072 19.47656 0.14062 5.43743 1e-4 11.01555 -0.0468 16.73437 -0.14062 -0.79695 9.93758 -1.41804 19.65242 -1.86328 29.14453 -0.44538 9.49224 -0.69148 16.67583 -0.73828 21.55078 2.24992 0.0938 4.89836 0.14067 7.94531 0.14062 2.39054 5e-5 3.77335 -0.0117 4.14844 -0.0352 0.37491 -0.0234 1.28898 -0.082 2.74219 -0.17578 -0.18759 5.62504 -0.28134 11.55472 -0.28125 17.78906 l 0 3.30469 c -2.81259 -0.18748 -6.96102 -0.28123 -12.44531 -0.28125 l -2.88282 0.0703 c -0.37507 4.54689 -0.56257 12.70313 -0.5625 24.46875 -4.64069 -0.0937 -9.44537 -0.14063 -14.41406 -0.14063 -4.64068 0 -9.75005 0.0469 -15.32812 0.14063 z m 5.83593 -44.22656 1.47657 -31.71094 c -3.0938 4.82819 -5.62505 8.67194 -7.59375 11.53125 -1.9688 2.85943 -3.39848 4.8985 -4.28907 6.11719 l -10.19531 14.0625 z" FillRule="NonZero"/>
                        </Path.Data>
                    </Path>
                    <Path xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="path2992" Fill="{StaticResource linearGradient3782}" StrokeThickness="4" Stroke="#FF000000" StrokeMiterLimit="4">
                        <Path.Data>
                            <PathGeometry Figures="m 200.78014 296.64789 c 0.18749 -2.20312 0.33983 -5.12109 0.45703 -8.75391 0.11718 -3.6328 0.26952 -7.34764 0.45703 -11.14453 4.87499 -3.98435 9.35155 -7.85153 13.42969 -11.60156 6.60934 -6.09371 12.46871 -11.81246 17.57812 -17.15625 4.07808 -4.26557 7.49996 -8.17963 10.26563 -11.74219 1.5937 -2.10931 2.64838 -3.86712 3.16406 -5.27344 0.37495 -0.98431 0.56245 -1.99212 0.5625 -3.02343 -5e-5 -1.35931 -0.30474 -2.5429 -0.91406 -3.55079 -0.60943 -1.00773 -1.57037 -1.8632 -2.88282 -2.5664 -1.31254 -0.70305 -2.90629 -1.26555 -4.78125 -1.6875 -1.87504 -0.4218 -4.00785 -0.63274 -6.39843 -0.63281 -3.28129 7e-5 -6.73831 0.28132 -10.3711 0.84375 -3.63283 0.56257 -8.58986 1.6407 -14.87109 3.23437 l 1.82812 -10.05469 c 0.42187 -2.01554 1.03124 -5.88272 1.82813 -11.60156 12.3281 -2.0624 23.88277 -3.09365 34.66406 -3.09375 4.92182 1e-4 9.63275 0.44541 14.13281 1.33594 4.49994 0.89072 8.53118 2.40244 12.09375 4.53515 3.56242 2.13291 6.2343 4.61728 8.01563 7.45313 1.78116 2.83602 2.67179 5.89461 2.67187 9.17578 -8e-5 2.15632 -0.25789 4.28913 -0.77343 6.39844 -0.51571 2.01569 -1.47665 4.38288 -2.88282 7.10156 -1.78133 3.37506 -3.98445 6.70318 -6.60937 9.98438 -3.8907 4.92192 -8.39069 10.00785 -13.5 15.25781 -4.87506 4.96878 -10.73443 10.5469 -17.57813 16.73437 l 7.73438 0.0703 c 1.82807 2e-5 5.44916 -0.0469 10.86328 -0.14063 5.41399 -0.0937 9.17571 -0.18748 11.28516 -0.28125 2.10929 -0.0937 4.71085 -0.30467 7.80468 -0.63281 -0.1407 2.25002 -0.36336 5.06251 -0.66797 8.4375 -0.30476 3.37501 -0.62117 7.5 -0.94921 12.375 -11.67195 -0.0937 -23.88287 -0.14063 -36.63282 -0.14063 -15.37503 0 -28.38282 0.0469 -39.02343 0.14063 z" FillRule="NonZero"/>
                        </Path.Data>
                    </Path>
                </Canvas>
            </Canvas>
        </Canvas>
    </Viewbox>
</Grid>

Here, the entire Viewbox element is generated by Inkscape.

Running the project outputs the number 42 as follows:

Beware of the Leopard

Will

Posted 12 years ago

Reputation: 39

+1 for boldly admitting you let an app generate the code for you. This 42 totally needs to drink a smart drink and rave all night. – Jonathan Van Matre – 12 years ago

4

Infinite Brainfuck

Maybe not creative, but it sure was time-consuming as f*ck. Given a Brainfuck program as input, it outputs an equivalent Brainfuck program that's twice as large.

Here's the code:

>>     >> >>>>>>
>>     >> >>>>>>>>>
>>     >>        >>>
>>     >>         >>
>>     >>        >>>
>>>>>>>>>      >>>
>>>>>>>>>    >>>
       >>  >>>
       >> >>
       >> >>
       >> >>>>>>>>>>
       >> >>>>>>>><<

<<     << <<<<<<
<<     << <<<<<<<<<
<<     <<        <,+
[-     --         --
--     --        --[
+++++++++      +--
---------    ---
       --  ---
       -- --
       -- --
       -- --->[-]+>[
       -] <<[+++++++

++     ++ ++++++
++     ++ +++++++++
++     >>        >>>
>>     >>         >+
++     ++        +++
+++++++++      +++
+++++++++    +++
       ++  +++
       >> >>
       >> >>
       >> ++++++++++
       ++ ++++++++++

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

<<     <+ <<<<<<
<<     << <<<<<<<<<
<<     <<        <<<
[<     <<         <<
<<     <<        <<<
<<<<<<<<<      <<<
<<<<<<]<<    <<]
       >>  >>>
       >> >>
       >> >>
       >> >>>>>>>>>>
       >> >>>>>>>[>>

>>     >> >>>>>>
>>     >> >>>>>>>>>
>>     >>        >]+
[<     <<         <<
<<     <<        <<<
<<<<<<<<<      <<<
<<<<<<]<<    <<+
       ++  +++
       ++ ++
       ++ ++
       ++ ++++++++++
       ++ ++++++++++

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

<<     << <<<<<[
<<     << <<<<<<<<<
<<     <<        <<<
<<     <<         <<
<<     <<        ]<<
<<]>>>>>>      >>>
>>>>>>>>>    >>>
       >>  >>>
       >> >>
       >> >>
       [> >>>>>>>>>>
       >> >>>>>>>>>>

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

>>     >> >>>>>>
>>     >> >>>>>>>>>
>>     >>        [>>
>>     >>         >>
>>     >>        >>>
>>>>>>>>>      >>>
>>>]<<<<+    <<<
       <<  <<<
       << <<
       << <<
       << <<<<<<<<[<
       << <<<<<<<<<<

<<     << <<<<<<
<<     << <<<]<<<<]
>>     >>        >>>
>>     >>         >>
>>     >>        >>>
>>>>>>>>>      >>>
>>[>>>>>>    >>>
       >>  >>>
       >> >>
       >> >>
       >> >>>>>>]+[<
       << <<<<<<<<<<

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

>>     >> >>>>>>
>>     >> >>>>>>>>>
>>     >>        ]<<
<<     +<         <<
<<     <<        <<<
<<<<<<<<<      <<<
<<<<[<<<<    <<<
       <<  <<<
       << <<
       << <<
       << <<<<<<<<]<
       << <]>>>>>>>>

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

++     ++ ++++++
++     ++ +++++++++
++     ++        ++>
>>     >>         >>
>>     >+        +++
+++++++++      +++
+++++++++    +++
       ++  +++
       ++ +>
       >> >>
       >> >>>+++++++
       ++ ++++++++++

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

>>     >> >>>>>>
>>     >> >>]<<<<+<
<<     <<        <<<
<<     <<         <<
<<     <<        <<<
<<<<<[<<<      <<<
<<<<<<<<<    <<<
       <<  <<<
       << <<
       << <]
       << <<]>>>>>>>
       >> >>>>>>>>>>

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

>>     >> >>>>>>
>>     >> >>>>>>>>>
>>     >[        >>>
>>     >>         >>
>>     >>        >>>
>>>>>>>>>      >>>
>>]<<<<+<    <<<
       <<  <<<
       << <<
       << <<
       << <<<<<<<[<<
       << <<<<<<<<<<

<<     << <<<<<<
<<     << <<]<<<<]>
>>     >>        >>>
>>     >>         >>
>>     >>        >>>
>>>>>>>>>      >>>
>[>>>>>>>    >>>
       >>  >>>
       >> >>
       >> >>
       >> >>>>>]+[<<
       << <<<<<<<<<<

<<     << <<<<<<
<<     << <<]<<<<<<
<<     <<        <<<
<<     <<         <<
<<     <<        <,-
---------      ]>>
>>>>>>>>>    >>>
       >>  >>>
       >> >>
       >> >>
       >> >>>>>>>>>>
       >> >>[>>>>>>>

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

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

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

++     ++ ++++++
++     ++ +++++++++
++     ++        +++
++     ++         <<
<<     <<        <<<
<<<<<<>>>      >>>
>>>>>>>>>    >>>
       >>  >>>
       >> >>
       >> >>
       >> [>>>>>>>>>
       >> >>>>>>>>>>

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

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

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

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

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

<<     << <<<[<<
<<     << <<<<<<<<<
<<     <<        <<<
<<     <<         <<
<<     ]<        <<<
>>>>>>>>>      >>>
>>>>>>>>>    >>>
       >>  >>>
       >> >>
       >> >>
       >> >>>>[>>>>>
       >> >>>>>>>>>>

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

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

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

++     ++ ++++++
++     ++ +++++++++
+<     <<        <<<
<<     <<         <<
<<     <<        <<<
<<<<<<>>>      >>>
>>>>>>>>>    >>>
       >>  >>>
       >> >>
       >> >>
       >> [>>>>>>>>>
       >> >>>>>>>>>>

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

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

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

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

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

<<     << <<<<<<
<<     << <<<[<<<<<
<<     <<        <<<
<<     <<         <<
<<     <<        <<<
<<<<<]<<<      <<<
<<<<<<<<<    <<<
       <<  <<<
       << <<
       << <<
       << <<<<<<<<<<
       << <<<<<<<<<,

+]     >> >>>>>>
>>     >> >>>>>>>>>
>>     >>        >>>
>>     >>         >>
>>     >>        >>>
>>>>>>>>>      >>>
>>>>>>>>>    >>>
       >>  >>>
       >> >>
       >> >>
       >> >>>>>>>>>>
       >> >>>>>>>>>>

And a snippet of the output that results when you run it with itself as input*.

>42*          >42*  >42*>42*>42*
>42*          >42*  >42*>42*>42*
>42*          >42*  >42*>42*>42*>42*>4
2*>4          2*>4  2*>42*>42*>42*>42*
>42*          >42*                >42*>4
2*>4          2*>4                2*>42*
>42*          >42*                  >42*
>42*          >42*                  >42*
>42*          >42*                >42*>4
2*>4          2*>4                2*>42*
>42*>42*>42*>42*>4            2*>42*
>42*>42*>42*>42*>4            2*>42*
>42*>42*>42*>42*>4        2*>42*
>42*>42*>42*>42*>4        2*>42*
              >42*    >42*>4
              2*>4    2*>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*<4
2*<4          2*<4  2*<42*<42*<42*<42*
<42*          <42*                <42*<4
2*<4          2*,4                2*+42*
[42*          -42*                  -42*
-42*          -42*                  -42*
-42*          -42*                -42*-4
2*-4          2*-4                2*[42*
+42*+42*+42*+42*+4            2*+42*
+42*+42*+42*+42*-4            2*-42*
-42*-42*-42*-42*-4        2*-42*
-42*-42*-42*-42*-4        2*-42*
              -42*    -42*-4
              2*-4    2*-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*

Note: EOL and EOF behavior varies by Brainfuck implementation and environment. This code expects a single 10 for EOL, and -1 for EOF.

* Theoretically. I couldn't actually get this to work -- it caused a segfault. But running it on smaller inputs worked.

pandubear

Posted 12 years ago

Reputation: 357

I don't agree that it's an "infinite brainfuck" if it requires input to run. If it were a proper quine (no input, copies itself as output) then it would be infinite. – grovesNL – 12 years ago

4

Python

Patterned from the Evolution of Text. Churns out random text, but keeps the parts that match your target.

Program:

import random,time

def joined(string):
    return ''.join(string)

print("The Evolution of the Question")
theQuestion = "The Answer to Life, the Universe and Everything is 42"
letters = [chr(i) for i in range(32,127)]
randomString = [random.choice(letters) for i in range(len(theQuestion))]
print("Our first guess:", joined(randomString))
nextGuess = list()

evol = 0
while joined(randomString) != theQuestion:
    nextGuess = list()
    evol += 1
    for i in range(len(randomString)):
        if randomString[i] == theQuestion[i]:
            nextGuess.append(theQuestion[i])
        else:
            nextGuess.append(random.choice(letters))
    print("Next:", joined(nextGuess))
    randomString = nextGuess
    time.sleep(0.5)

print("in {} generations.".format(evol))

Output:

The Evolution of the Question
Our first guess: :Z[_8v~(sH!F'^[8D*g4*vTa|gDa/ 6evII&]Ni{SIixV7jq=7u8e
Next: F9p\pS,IF5sBOA<J<QfYd}Fm!93r~LQeQ|aY60v%lNx!z!Dt8]@r\
Next: |(E\V5>:zJ"<:?1p}}Y`EjyY|X<v#jheSTt1*(v_! Io{N%')wpoh
Next: d@o6x4/*{: @PLXV`>aF9p53+f`v/-<e|,21_evFH>zqx$RBw(8YU
Next: y7ZT>cNqfr ;Od7]@w.~)yDVEdwv6IgeFWWJA.vbr!wr*Gy_3MJ(&
Next: ^A$Ea\L5Kr Vd-TnL;m5%nh32OkvZ4_eJGJuHsvsrSw<l`&AoK,HC
Next: (MRnA,.Myr gwqpj!+!Ow&li;?Fv0}fe0B5UeEv;r-nPw:P9hgupw
Next: Pba4Ak5"pr s|mHq<sFDAqQJTd]vSk0eS0yf$EvTr=&m+V)@T7O y
Next: HcmVA<qn\r qG2!|Aa\*c[ ghS4v;y e]<aB1Ev`rv?$c\QGy`GTq
Next: [cR/A$;r,r ziXe}%Rqli)6+=Sgvc\Le2BF!bEvFrc\1dP'Z.+^9I

and 300-400+ evolutions later...

Next: The Answer to Life, tRe Universe and Everything is 42
Next: The Answer to Life, tFe Universe and Everything is 42
Next: The Answer to Life, t%e Universe and Everything is 42
Next: The Answer to Life, t)e Universe and Everything is 42
Next: The Answer to Life, tke Universe and Everything is 42
Next: The Answer to Life, tke Universe and Everything is 42
Next: The Answer to Life, the Universe and Everything is 42
in 498 generations.

Dan the Man

Posted 12 years ago

Reputation: 141

4

ised

ised '[]'

It's an easter egg... an empty constructor returns 42!

This would probably win a code-golf entry (with only 2 characters), but for a popularity contest, it's just an interesting piece of information :)

orion

Posted 12 years ago

Reputation: 3 095

4

Bro... no...

This is how you output 42:

import Control.Monad                --               _                       _
                                    --              | |                     | |
bros :: (Integral n, Monad m)       --            =H| |=====mn=======nm=====| |H=
     => (n -> n) -> m n -> m n      --              |_|     ( \     / )     |_| 
bros = do                           --                       \ )(")( /
       you even                     --                       ( /\_/\ )
       liftM                        --                        \ 4 2 /
  where                             --                         )=O=(
    you = liftM                     --                        /  _  \
                                    --                       /__/ \__\
fact = sum . bros succ . tail       --                       | |   | |
                                    --                       |_|   |_|
main = print $ fact [1..8]          --                       (_)   (_)

recursion.ninja

Posted 12 years ago

Reputation: 548

4

C++, It's Not Always Sunny Over There

Edit:

1) I don't need the average velocity anymore thanks to the 3rd Kepler's law (see how the period is computed; 92955807 because 1 AU = 92955807 miles). 2) Use of TAU instead of PI.

Version 1

#include <iostream>
#include <cmath>

#define TAU 6.283185307179586
#define D double

int north;

int main(){

    D theta = 0.000001;

    D farthest = 1868039489; // miles
    D closest = 1699449110; // miles
    D eccentricity = 0.04725744;

    D a = (closest + farthest) / 2;
    D b = (a * 2 * sqrt(1 - pow(eccentricity, 2))) / 2;
    D period = sqrt(pow(a / 92955807, 3));

    for (D t = 0; t < TAU; t += theta) if (b * sin(t) >= 0) north++;

    std::cout << (int)(north * period / (TAU / theta));

}

Output:

42

Indeed:

Summer on northern hemisphere of Uranus lasts 42 years per period.

Explanation:

Only using perihelion and aphelion [closest and farthest distance to the sun] and orbit eccentricity [data from NASA], my program simulates, at the highest level of abstraction and in an extremely simplified way, the rotation of Uranus around the sun. enter image description here


Version 2

#include <iostream>
#include <cmath>

#define TAU 6.283
#define D double

int north;

bool incidence(D t, D tilt) {
    int i = (int)(t * 57.295 + tilt) % 360;
    return i >= 90 && i <= 270;
}

int main(){

    D theta = 0.00001;

    const D orbit_size = 19.189165; // AU
    const D axial_tilt = 97.77; // degrees

    D period = sqrt(pow(orbit_size, 3));

    for (D t = 0; t < TAU; t += theta) if (incidence(t, axial_tilt)) north++;

    std::cout << (int)((north * period) / (TAU / theta));

}

In this version, only the size of the orbit (= semi major axis, in AU) and the axial tilt of Uranus are used. The program computes the orbit period with the third Kepler's law. The way sunlight reaches the planet is computed thanks to the t angle (radians) converted to degrees (* 57.295) plus the axial tilt. North is lighted up when this angle is between 90° and 90+180°. enter image description here

Display_name

Posted 12 years ago

Reputation: 330

Just adding to the amounting proof that it is actually embedded in our universe. – ASCIIThenANSI – 11 years ago

3

C

I guess you should know what the output is:

#include<stdio.h>
int main()
{
    printf("       :::::::::  ::::::::::::::::\n");
    printf("      ::::::::::  ::::::::::::::::::\n");
    printf("     :::::::::::  :::::::::::::::::::\n");
    printf("    ::::::::::::  :::::::     ::::::: \n");
    printf("   :::::: ::::::              :::::::\n");
    printf("  ::::::  ::::::              :::::::\n");
    printf(" ::::::   ::::::           ::::::::: \n");
    printf("::::::::::::::::::    :::::::::::::  \n");
    printf("::::::::::::::::::  :::::::::::::    \n");
    printf(":::::::::::::::::: :::::::::::       \n");
    printf("          ::::::   :::::::          \n");
    printf("          ::::::   :::::::          \n");
    printf("          ::::::   :::::::       ::::::\n");
    printf("        :::::::::: ::::::::::::::::::::\n");
    printf("        :::::::::: ::::::::::::::::::::\n");
    printf("        :::::::::: ::::::::::::::::::::\n");

    return 0;
}

Mhmd

Posted 12 years ago

Reputation: 2 019

3

C

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

Guest1

Posted 12 years ago

Reputation: 31

3I don't get the trick is it about the missing semicolon at the end? – Mhmd – 12 years ago

It outputs 42 in binary which is 101010 (32+8+2)... – Axel – 12 years ago

3

Ruby

six = '1 + 5'
times = 42.chr
nine = '8 + 1'

p eval [six,times,nine].join

histocrat

Posted 12 years ago

Reputation: 20 600

1

This has the same logic of this: http://codegolf.stackexchange.com/a/16682/12205

– user12205 – 12 years ago

We're both referencing the same thing. – histocrat – 12 years ago

3

Javascript

var s = this.toString().split(" ")[1].replace("]","").toLowerCase() + Math.sqrt(123 ^ 0.5).toString().charAt(2) + atob("bG9jYXRpb24=") + String.fromCharCode((4 * 4 * 4).toString().charAt(1) + (Math.log(4 * 4 * 4) / Math.log(2)));
for (var i = 0; i < "roy eats pea lasagne and crunchy eggs!".split(" ").length; i++) {
    s += "roy eats pea lasagne and crunchy eggs".split(" ")[i].charAt();
}
s += String.fromCharCode(5 * Math.pow(2, 3)) + "\"data:text/text,";
var i = 21,
    o = 21;
while (i != Math.floor(i) || i == 21) {
    i += o;
    o /= 2;
}
s += i + s.charAt(24) + String.fromCharCode(s.charCodeAt(23) + 1);
window.location.replace("javascript:" + s);

Output:

window.location.replace("data:text/text",42);

Output's output:

42

kitcar2000

Posted 12 years ago

Reputation: 2 689

3

Haskell

h2g2          = fromIntegral
douglasAdams  = length
l x           = 1 / h2g2 (douglasAdams x)
the x         = h2g2 $ sum $ zipWith (*) (map douglasAdams x) [0,1,-1]
theanswerisfoundin theRestaurantAtTheEnd= print $ round theRestaurantAtTheEnd

main=theanswerisfoundin 
     (the ["Hitch" ,"Hikers" ,"Guide"] / (l "TO" - l "THE" - l "GALAXY!")) 

How it works

It outputs 1/ (1/2 - 1/3 - 1/7) :)

RobAu

Posted 12 years ago

Reputation: 641

3

Befunge-93

I guess this is not very creative but since there are several brainf*ck answers, I feel like good old befunge-93 should get his moment too. I did try to use some of the cool features of the language such as self-modification and a trampoline.

                                                                               v
           What is the answer to life, the universe, and everything?           
                                   >   v
                 DON'T                             PANIC
v:                                "6 * 9"                                      <
_v#                                                                           :,
 >       1v        <     >         ^   >            *.@
v****22222< >79*2-,^
>,          |         
            >56+5*58*1-4p^

And the output is of course:

 6 * 9 = 42

Simbilou

Posted 12 years ago

Reputation: 31

3

Mathematica

Ceiling[E^(E + E^(E - E))]

martin

Posted 12 years ago

Reputation: 1 335

Which language is this? – Victor Stafusa – 12 years ago

@ Victor, Mathematica – martin – 12 years ago

1Ok, I recommend that you always put the used language in the title and ident source-code with four spaces (so the site identifies it as source-code). I did this for you here. – Victor Stafusa – 12 years ago

3

Python

import math
print ((math.floor(e)*math.floor(e))*(math.ceil(pi*pi)))+math.floor(e)

Actually, you can print every integer using this method. It's your job to find it . . . .

Gavriel Feria

Posted 12 years ago

Reputation: 51

3

In the language whose name is the first three letters of Douglas Adams' last name:

Ada

with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Print_42 is
    S: String(1..6);
begin
    Ada.Integer_Text_IO.Put(To => S, Item => 6 * 9, Base => 13);
    Ada.Text_IO.Put_Line(S(4..5));
end Print_42;

Keith Thompson

Posted 12 years ago

Reputation: 289

3

C#

There's a clear dependency between the phrase and the hashes:

using System;
using System.Security.Cryptography;
using System.Text;

class C
{
    static void Main ()
    {
        byte[]b=Encoding.ASCII.GetBytes("Answer to the Ultimate Question of Life, the Universe, and Everything");
        Func<HashAlgorithm,int>q=a=>a.ComputeHash(b)[0];
        int[]i={ q(MD5.Create()), q(SHA1.Create()), q(SHA256.Create()), q(SHA384.Create()), q(SHA512.Create()) };
        Console.WriteLine((i[0]+i[1]+i[2]+i[3]+i[4])/(i[2]-i[1])+1);
    }
}

Is it a coincidence or a sign?

Athari

Posted 12 years ago

Reputation: 2 319

3

Python

print reduce(lambda x, y: x ^ ord(y), 'Life, the universe and everything', 6 * 9)

VisioN

Posted 12 years ago

Reputation: 4 490

3

Python (But not specific to Python...)

print(((True<<((True<<((True<<True)+True))+True))/(True<<((True<<(True<<True))+(True<<True)))-True)*((True<<(True<<True))+(True<<True)))

EDIT:

Slightly nicer (and 42 non-whitespace characters...)
Only works in Python 2.x though.

print (1<<1<<(1<<1<<1))+(1<<1<<1<<1)+(1<<1)

daviewales

Posted 12 years ago

Reputation: 271

3

Perl

another try - reads as assembly, parses as perl, includes "DON'T PANIC" and displays 42 :)

use v5.10;

* DON::T = sub {
    s   mm
    pop me, y

    - Douglas N. Adams 
    - a short fanfare

    (-;

    s   0.0
    g   x 
    hex $&, 0eg
    and do
    say tr

    - Ford Prefect
    - Arthur Dent

    c-c
};

DON'T PANIC

chinese perl goth

Posted 12 years ago

Reputation: 1 089

3

Bash:

expr "`echo "The answer to Ultimate Question of Life, the Universe, and Everything" | wc -l`" \* "`echo "Here it goes" | wc -l`" \* "`echo "Life," | wc -c`" + "`echo "The Unviverse," | wc -c`" + "`echo "And Everything..." | wc -c`" + "`echo "The Answer is" | wc -w`"

Output:

42

thecrazurious

Posted 12 years ago

Reputation: 51

Could you format this in a way that is readable on Stack Exchange? E.g. using four leading spaces (code formatting) and some line breaks? Maybe also use $(...) instead of the backticks ``? – Paŭlo Ebermann – 12 years ago

3

Simple but efficient python one-liner.

>>> sum([ord(x) for x in 'THE UNIVERSE FINAL ANSWER']) // 42
42

Balthazar Rouberol

Posted 12 years ago

Reputation: 131

Nice. But better use // (integer division) to make it work in Python 3 too. (Otherwise the result would be 42.19047619047619.) – manatwork – 12 years ago

3

Wang B-machine

Of course the B-machine doesn't have a graphical output, but if you interpret the final tape as a 9x6 font...

{ (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, *), (41, →),
(42, *), (43, →), (44, *), (45, →), (46, *), (47, →), (48, →), (49, →), (50, *), (51, →),
(52, →), (53, →), (54, →), (55, →), (56, *), (57, →), (58, →), (59, →), (60, *), (61, →),
(62, →), (63, →), (64, →), (65, →), (66, →), (67, *), (68, →), (69, →), (70, *), (71, →),
(72, *), (73, →), (74, *), (75, →), (76, *) }

Oberon

Posted 12 years ago

Reputation: 2 881

3

Piet

This is my first attempt at a program in Piet.
It prints 42 indefinitely:

enter image description here

It simply multiplies 6 by 7 and outputs, so nothing really fancy, I just wanted to give Piet a try.
It is somewhat golfed though as it consists only of 18 codels.

plannapus

Posted 12 years ago

Reputation: 8 610

3

JavaScript

I probably could have done something more creative than this, but:

var ArrayToLifeTheUniverseAndEverything=[
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,1,0,0,1,1,1,1,1,0,0,0,1,0],
[0,1,0,0,1,0,0,0,0,0,0,0,1,0,0,1,0],
[0,1,0,0,1,0,0,0,0,0,0,0,1,0,0,1,0],
[0,1,0,0,1,0,0,0,0,0,0,0,1,0,0,1,0],
[0,1,1,1,1,0,0,0,0,0,0,0,1,0,0,1,0],
[0,0,0,0,1,0,0,0,1,1,1,1,0,0,0,1,0],
[0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,1,0],
[0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,1,0],
[0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,1,0],
[0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,1,1,1,1,1,0,0,1,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]];

var DouglasAdams =""

for(var DontPanic = 0; DontPanic<ArrayToLifeTheUniverseAndEverything.length; DontPanic++){
    for(var FriendlyLetters = 0; FriendlyLetters<ArrayToLifeTheUniverseAndEverything[DontPanic].length; FriendlyLetters++){
        if(ArrayToLifeTheUniverseAndEverything[DontPanic][FriendlyLetters]){
            DouglasAdams+="*";
        }else{
            DouglasAdams+=" ";
        }
    }
    DouglasAdams+="\n"
}
console.log(DouglasAdams);

But as a bonus, as I saw someone else say earlier, the ASCII code for * is 42.

potato

Posted 12 years ago

Reputation: 111

3

C

main(){printf((char[]){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>>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,(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+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/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)/(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/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/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>>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});return 42;}

This outputs "The answer to life, the universe and everything." using (almost) only the number 42. Additionally, it returns 42.

Christoph Böhmwalder

Posted 12 years ago

Reputation: 681

2

F#

let answer = 42
[|62; 74; 74; 70; 73; 16; 5; 5; 77; 77; 77; 4; 61; 69; 69; 61; 66; 59; 4; 57;
  69; 67; 5; -7; 71; 19; 74; 62; 59; 1; 55; 68; 73; 77; 59; 72; 1; 74; 69; 1;
  66; 63; 60; 59; 1; 74; 62; 59; 1; 75; 68; 63; 76; 59; 72; 73; 59; 1; 55;
  68; 58; 1; 59; 76; 59; 72; 79; 74; 62; 63; 68; 61|]
|> Array.map (((+) answer) >> char)
|> (fun c -> new string(c))
|> System.Diagnostics.Process.Start

It navigates to https://www.google.com/#q=the+answer+to+life+the+universe+and+everything

Jwosty

Posted 12 years ago

Reputation: 3 530

2

Perl

#!/usr/bin/perl
package Six;
use overload '*' => sub { return "42\n" };
sub multiplied { return bless {}, shift };
sub by { shift };
sub nine { shift };
sub equals { $six=shift;  return $six*$nine };

package main;

print Six->multiplied->by->nine->equals

keepcalm

Posted 12 years ago

Reputation: 121

3Welcome to Code-Golf! Don't forget to add an explanation on why this answer is creative! – Justin – 12 years ago

2

PHP + Google

header("Location: http://www.google.com/#q=the+answer+to+life+the+universe+and+everything");

If you really type The answer to life the universe and everything in Google, it will output 42.

Vereos

Posted 12 years ago

Reputation: 4 079

Oh, did not see that someone else had the same idea, just a few minutes before I posted my version of this answer – RononDex – 12 years ago

2

Google

Enter "the answer to life the universe and everything" into the search bar of google:
https://www.google.ch/search?q=the+answer+to+life+the+universe+and+everything

I am aware that this is not actually source code that executes. However the OP did not state that is has to be written in a programming language or that it should result in a executable file.

RononDex

Posted 12 years ago

Reputation: 274

2

Python 3

Example from real-life (translated to english). One of the python3 student tasks was writing a program that outputs string with user name to both screen and file. The student program was:

protocol_file = open("protocol.txt", "wt")
name = input("Enter your name: ")
print(protocol_file.write("Judge says:  Do you admit your guilt, " + name + "?\n"))
protocol_file.close()

For testing purposes student inputs some two-letter garbage as name - "mg". ... and, got 42 printed in console.

Vasily Galkin

Posted 12 years ago

Reputation: 21

2

bash 732

Where 7, 3 and 2 are the primes that compose 42!!

#!/bin/bash

export ResultString

export MaxToReach=${RANDOM}{0,}

for ((CurrentVal = MaxToReach ; CurrentVal-- ;-p))
do
   ((
     ( CurrentVal + CurrentVal ) == ( CurrentVal * CurrentVal ) &
     ( CurrentVal * CurrentVal ) == ( CurrentVal ** CurrentVal )
   )) &&
     printf -v ResultString "%01d%01d" $((
          CurrentVal ** CurrentVal
          )) $CurrentVal
done

AltCheck=$(stat -c %s $0)
for (( I = ${#AltCheck} ; I-- ;-p))
do
     AltResult=${AltCheck:I:1}*$AltResult
   done

cat <<EndOfFinalAnswer
DISCLAIMER: This tool would help you to compute the answer!
Unfortunely, this tool is unable to retrieve THE question.

The answer to the ultimate question is: '$ResultString' or '$((${AltResult}1))'!
EndOfFinalAnswer

Running this very usefull tool will print:

DISCLAIMER: This tool would help you to compute the answer!
Unfortunely, this tool is unable to retrieve THE question.

The answer to the ultimate question is: '42' or '42'!

F. Hauri

Posted 12 years ago

Reputation: 2 654

2

Binary

101010

is 42 in binary and the meaning of life...;-)

I owe, I owe, I owe. (it's off to work I go.)

Kevin

Posted 12 years ago

Reputation: 29

@Kevin if you're trying to quote that song from Snow White, you should only say "I owe" twice. – mbomb007 – 11 years ago

2This is a programming contest, not a poetry contest. – user12205 – 12 years ago

I edited your answer to change it to a more acceptable format. Next time, write your answers more like this. – Justin – 12 years ago

Who you owe? What do you owe them? Maybe you should pay them back... – DaveRandom – 11 years ago

2

Perl evil answer (42)

( $E666 = 666 )=~s/.//;printf "%x\n",$E666

Running demo:

perl -e '( $E666 = 666 )=~s/.//;printf "%x\n",$E666'
42

F. Hauri

Posted 12 years ago

Reputation: 2 654

2

HTML & CSS

It's ugly and probably not compatible with all browsers, but here we go:

    <span style="display: inline-block; width: 3em; height: 3em">
    <span style="position: relative; display: inline-block; width: 3em; height: 3em">
        <i style="position: absolute;display:inline-block;width:0;height:0;line-height:0;border:1.5em solid #000000;border-bottom:none;border-top-right-radius:1.5em;border-top-left-radius:1.5em;left:4em;top:0em"></i>
        <i style="position: absolute;display:inline-block;width:0;height:0;line-height:0;border:1.3333333333333333em solid #ffffff;border-radius:1.3333333333333333em;left:4.166666666666666em;top:0.16666666666666666em"></i>
        <i style="position: absolute;display:inline-block;width:0;height:0;line-height:0;border:1.5em solid transparent;border-right:1.5em solid #000000;border-bottom:1.5em solid #000000;left:4em;top:1.3333333333333333em"></i>
        <i style="position: absolute;display:inline-block;width:0;height:0;line-height:0;border:1.3333333333333333em solid transparent;border-right:1.3333333333333333em solid #ffffff;border-bottom:1.3333333333333333em solid #ffffff;left:4.333333333333333em;top:1.6666666666666665em"></i>
        <i style="position: absolute;display:inline-block;width:3em;height:0.16666666666666666em;background-color:#000000;left:4em;top:4.333333333333333em"></i>
        <i style="position: absolute;display:inline-block;width:0.16666666666666666em;height:4.5em;background-color:#000000;left:1.8333333333333333em;top:0em"></i>
        <i style="position: absolute;display:inline-block;width:3em;height:0.16666666666666666em;background-color:#000000;left:0em;top:1.5em"></i>
        <i style="position: absolute;display:inline-block;width:0.16666666666666666em;height:1.6666666666666665em;background-color:#000000;left:0em;top:0em"></i>
    </span>
</span>

Which outputs

enter image description here

In Chrome at least... Here's the fiddle: http://jsfiddle.net/myJC4/

Dryden Long

Posted 12 years ago

Reputation: 217

1Works fine in Opera ;3 – cjfaure – 12 years ago

2

Bash:

$ expr "`whatis "the answer to Ultimate Question of Life, the Universe, and Everything" 2>&1 | wc -c`" - "`echo "Really, what it is?" | wc -c`" - "`echo "For god sake, please tell me." | wc -c`"

Output is: 42

thecrazurious

Posted 12 years ago

Reputation: 51

2

JavaScript

String.prototype.repeat = function( num )
{
    return new Array( num + 1 ).join( this );
};
var four='4';
var two='2';

var firstLineFour=four+' '.repeat(5)+four;
var secondLineFour=' '.repeat(6)+four;
console.log(
    (firstLineFour+' '+two.repeat(7)+'\n'+firstLineFour+' '.repeat(7)+two+'\n'+four.repeat(7)+' '+two.repeat(7)+'\n')+((secondLineFour+' '+two)+'\n')+(secondLineFour+' '+two.repeat(7))+'\n'
);

Output:

4     4 2222222
4     4       2
4444444 2222222
      4 2
      4 2222222

The variable four is set to '4' and two set to '2', but you can change them to make it "draw" with different numbers.

Cilan

Posted 12 years ago

Reputation: 724

2

JavaScript (or ActionScript 3)

"What do you get if you multiply 6 times 9?".length

Result:

42

IQAndreas

Posted 12 years ago

Reputation: 1 180

2

Non-Alphanumeric JavaScript

[][(__=''+!!(_=+[]))[_$=-~-~-~_]+($$=''+{})[$=-~_]+($_=''+!_)[$]+$_[_]][$$[-~($+_$)]+$$[$]+(''+$/_)[$]+__[_$]+$_[_]+$_[$]+$_[$+$]+$$[-~($+_$)]+$_[_]+$$[$]+$_[$]](__[$]+__[$+$]+$_[_$]+$_[$]+$_[_]+"("+((($<<($<<$)^$)<<($<<$)^$)<<$)+")")()

The real secret is in ((($<<($<<$)^$)<<($<<$)^$)<<$) which does the real dirty work in generating the 42 from bitwise operators based off a single variable, $ which is worth 1.

WallyWest

Posted 12 years ago

Reputation: 6 949

2

C

#include <stdio.h>

int main()
{
  int answer = 6*9;
  char* wanted;
  for (wanted = "answer"; *wanted; wanted++)
    answer ^= *wanted;
  printf("%d\n", answer);
  return 0;
}

celtschk

Posted 12 years ago

Reputation: 4 650

2

k4

  */.:'(-;*;^)
42

Sometimes, k is a language only a Vogon could love....

Aaron Davies

Posted 12 years ago

Reputation: 881

2

Now that I know that desmos is a valid language... at least, for these purposes.

:D

View the result here!

You also may notice that it only uses (asides from the instance of 10, an instance of 1 and the three instances of e) the numerals 4 and 2.

Conor O'Brien

Posted 12 years ago

Reputation: 36 228

1

PYTHON

import webbrowser
webbrowser.open('http://t2.gstatic.com/images?q=tbn:ANd9GcTBdE69EouKgYcnWjjFko7Jx2gBgTVLu-n-tIn3QSu8EHhOJ_GsTxSwGVfD')

chack008

Posted 12 years ago

Reputation: 23

1

C#

Most everyone is connected in our daily lives. How about using the internet? Also, we judge web pages by their titles, so hopefully there is something useful in there.

using System;
using System.Net;

public class Universe {
 public static void Main(String[] args) {
    Byte[] EncodedAnswerPage = new Byte[] { 104,116,116,112,115,58,47,47,99,111,100,101,103,111,108,102,46,115,116,97,99,107,101,120,99,104,97,110,103,101,46,99,111,109,47,113,117,101,115,116,105,111,110,115,47,50,49,56,51,53,47,109,111,115,116,45,99,114,101,97,116,105,118,101,45,119,97,121,45,116,111,45,100,105,115,112,108,97,121,45,52,50 };
    WebClient Client = new WebClient();
    String s;
    try
    {
        s = Client.DownloadString(System.Text.Encoding.ASCII.GetString(EncodedAnswerPage)).Replace("\r\n", "");
    }
    catch (WebException)
    {
        Console.WriteLine("Sorry, I have failed you!!! I cannot give you the answer to life, the universe and everything.");
        Environment.Exit(42);
        return;
    }
    Console.WriteLine("The answer to life, the universe and everything is...");
    System.Threading.Thread.Sleep(2000);
    Console.WriteLine("6 * 7, which equals " + s[42 + 50] + "" + s[42 + 51]);
    Console.ReadLine();
            Environment.Exit(42);
 }
}

Justin Krejcha

Posted 12 years ago

Reputation: 227

1

Javascript:

console.log("The answer to life, the universe, and everything is elite pie.");
console.log(Math.round(Math.PI * 13.37));

user241920

Posted 12 years ago

Reputation: 31

1

Ruby

puts "the answer to life, the universe, and everything: ".tap{|n|$><<n}.split.map(&:ord).inject(-2){|a,b|a+b*(-1)**b}

afuous

Posted 12 years ago

Reputation: 429

1

PHP

Going really short with this... ord() will return ASCII value as an int for * character which is 42

<?=ord('*'); //Outputs 42

Demo

Mr. Alien

Posted 12 years ago

Reputation: 141

1

My faithful represntation of Deep Thought's great computation.

Haskell:

import Data.Char
import Math.NumberTheory.Primes
import System.IO

main =    putStrLn message
     >>   hSetBuffering stdin NoBuffering
     >>   getChar
     >>= (putStrLn . process)
  where
    process xs
      | confirm xs = (++) " [>]: " . show $ compute xs
      | otherwise  = failure
    message =  "\n [!] Press ENTER to confirm computation of the following query: \n"
            ++ "\n [?] Answer to the Ultimate Question of Life, the Universe, and Everything"
    failure =  "\n [X] Confirmation failed, computation aborted"
    confirm = (=='\n')
    compute = succ . sum . flip takeWhile primes . flip (<=)
            . (+) ((!!) primes . fromIntegral $ head primes)
            . fromIntegral . ord

Note that this may out-perform Deep Thought's original computation on your machine. If so, it's only because Deep Thought lacked a version of GHC which targeted it's architecture natively.

recursion.ninja

Posted 12 years ago

Reputation: 548

1

Obligatory Golfscript solutions:

"Answer To Life The Universe And Everything",

"The Hitchhiker's Guide to the Galaxy"{+}*
"Douglas Noel Adams"{+}*
-`{42-}%{+}*)

"DA"{64-}%{}/)

Josiah Winslow

Posted 12 years ago

Reputation: 725

The first one is the best! – theonlygusti – 11 years ago

1

Cartesian Function

Graph this on a coordinate plane.

((4x+9)sqrt(|.25-|x+1.75||/(.25-|x+1.75|))-y)((4x+5)sqrt(|.5-|x+1||/(.5-|x+1|))-y)(sqrt(|.75-|x+1.25||/(.75-|x+1.25|))-y)(3sqrt(|.5-|x-.5||/(.5-|x-.5|))-y)((4x-1)sqrt(|.25-|x-.75||/(.25-|x-.75|))-y)(2xsqrt(|.5-|x||/(.5-|x|))-y)(-sqrt(|.5-|x||/(.5-|x|))-y)=0

Josiah Winslow

Posted 12 years ago

Reputation: 725

1

Ti-84 BASIC

6*9→rand:randInt(1,42+42+42+422)

SuperJedi224

Posted 12 years ago

Reputation: 11 342

1

TI-BASIC

Gah, I've had this forever waiting for a place to use it... it's pretty much exactly the same as the top answer, though. Whatever, here it is!

1.25→F
F-.01(ᴇ2fPart(F→O
6.4(.01(ᴇ2fPart(F→R
tanh(Fᴇ9→T
F17.6→Y

√((2.96296296296296)(1.35→W

Disp FORTY-TWO⁻

M. I. Wright

Posted 12 years ago

Reputation: 849

1

JavaScript

It's a canoe race! Who will win?

 ~     ~     ~   ~ ~(~!~[]*~[]*~4)+  ~
  ~  +[] +[] +[]+    ~  ~    ~ ~
   ~ ~   ~!~[[[]]]*~[]-~[]+  ~  ~ +[~0]+~~1

Florrie

Posted 12 years ago

Reputation: 831

1

Here's another one:

JAVA

import java.awt.Font;
import java.awt.TextArea;
import java.awt.TextComponent;
import java.util.Random;

import javax.swing.JFrame;

public class FortyTwo {
    static Random r=new Random();
    static String pickOne(String[]s){
        return s[r.nextInt(s.length)];
    }
    public static void main(String[]a){
        double pi=3;
        double count=0;
        long in=0;
        String[]one={
                "Analyzing",
                "Bloxing",
                "Copying",
                "Hypnotizing",
                "Importing",
                "Indexing",
                "Initializing",
                "Loading",
                "Locating",
                "Polarizing",
                "Refactoring",
                "Resizing",
                "Scanning",
                "Synchronizing",
                "Updating"
        };
        String[]two={
                "Altairian",
                "Bistromathic",
                "Hooloovoo",
                "Hyperwave",
                "Logical",
                "Magrathean",
                "Optical",
                "Prismatic",
                "Probability",
                "Quantum",
                "Sub-Etha",
                "Tangential"
        };
        String[]three={
                "Circuit",
                "Dictionary",
                "Drive",
                "Engine",
                "Grid",
                "Mainframe",
                "Matrix",
                "Library",
                "Loop",
                "Utilities"
        };
        System.out.print(">>");
        try {
            Thread.sleep(200+r.nextInt(100));
        } catch (InterruptedException e) {}
        for(char c:"What is the answer to the ultimate question about life, the universe, and everything?".toCharArray()){
            try {
                Thread.sleep(70+r.nextInt(30));
            } catch (InterruptedException e) {}
            System.out.print(c);
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {}
        System.out.println();System.out.println();
        System.out.print(pickOne(one)+" "+pickOne(two)+" "+pickOne(three)+"... ");
        final int tot=500+r.nextInt(200);
        int l=0;
        int q=300+r.nextInt(800);
        int z=15+r.nextInt(5);
        long t=System.currentTimeMillis()+q;
        while(l<tot){
            in+=Math.pow(Math.random(),2)+Math.pow(Math.random(),2)<1?1:0;
            boolean S=Math.random()<0.012;
            count++;
            pi=(pi+4*in/count)/2;
            if(System.currentTimeMillis()>t){
                z--;
                System.out.println(S?"FAILED":"Done.");
                if(S){
                    try {
                        Thread.sleep(100+r.nextInt(50));
                    } catch (InterruptedException e) {}
                    System.out.println("Attempting alternate route.");
                    try {
                        Thread.sleep(500+r.nextInt(80));
                    } catch (InterruptedException e) {}
                    if(z==0)z+=r.nextInt(3)+1;
                }
                if(z==0){
                    z=20+r.nextInt(10);
                    int percent=(1000*l)/tot;
                    System.out.println((percent/10)+"."+(percent%10)+"% complete.");
                }
                System.out.print(pickOne(one)+" "+pickOne(two)+" "+pickOne(three)+"... ");
                if(!S)l+=q/300;
                t+=q=300+r.nextInt(800);
            }

        }
        System.out.println("Done.");
        System.out.println("=CALCULATIONS COMPLETE=");
        JFrame frame=new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("The answer to the ultimate question about life, the universe, and everything is:");
        frame.setVisible(true);
        frame.setBounds(frame.getX(),frame.getY(),600,150);
        TextComponent c=new TextArea();
        c.setText(String.valueOf((int)(13.37*pi)));
        c.setBounds(0,0,600,100);
        c.setFont(new Font("Verdana",Font.PLAIN,96));
        frame.add(c);
    }
}

Prints randomly generated technobabble (at present, there are 1,800 possible phrases) while performing a Monte Carlo approximation of pi, then creates a window with the floor(13.37*pi)=42 as its contents

SuperJedi224

Posted 12 years ago

Reputation: 11 342

0

Matlab

This function asks Wolfram Alpha "what is the meaning of life?", returns the HTML of the page to a string, then finds and outputs the input interpretation and result.

d=urlread('http://www.wolframalpha.com/input/?i=what+is+the+meaning+of+life%3F');
k=strfind(d,'"stringified": "');
q=strfind(d,'","mInput":');
disp(['Input interpretation: ' d(k(1)+16:q(1)-1)])
fprintf(['Result: ' d(k(2)+16:q(2)-1) '\n'])

Output:

Input interpretation: Answer to the Ultimate Question of Life, the Universe, and Everything

Result: 42

(according to Douglas Adams' humorous science-fiction novel The Hitchhiker's Guide to the Galaxy)

Moriarty

Posted 12 years ago

Reputation: 119

0

><>

I made a bunch of these, so here they are.

1111111111111++++++$+++++++*n; 42$~:42$/42$~*+*:42$/42$~*+*n; !;3!na!+*!+9!3| 'douglas adams'42$nn; 42*:1+*n;

Oh, and then there's this one.

0aa**3a*2++o0aa**3a*2++o0aa**5a*1++o0aa**3a*2++o0aa**3a*2++o0aa**3a*2++o0aa**9a*7++o0aa**9a*2++oao0aa**3a*2++o0aa**4a*7++o0aa**4a*3++o0aa**3a*2++o0aa**3a*2++o0aa**3a*2++o0aa**3a*2++o0aa**3a*2++o0aa**9a*2++oao0aa**4a*7++o0aa**3a*2++o0aa**4a*8++o0aa**3a*2++o0aa**3a*2++o0aa**3a*2++o0aa**3a*2++o0aa**4a*2++oao1aa**1a*0++o0aa**4a*7++o1aa**2a*4++o0aa**4a*5++o0aa**3a*2++o0aa**3a*2++o0aa**5a*9++oao0aa**3a*2++o0aa**3a*2++o0aa**9a*2++o0aa**3a*2++o0aa**3a*2++o0aa**4a*3++o0aa**5a*7++o0aa**4a*7++o0aa**9a*2++oao;

It prints 42 in ascii art, and if you run it as ><> again, you get 42.

Try it all here.

clap

Posted 12 years ago

Reputation: 834

0

Java

public class Hello42 {
static int i=8;

static public enum Enum42{
    ONE(),TWO();
    Enum42(){
        System.out.print(i/=2);
    }
}

public static void main(String[] args) {
     Enum42.values();
}
}

user902383

Posted 12 years ago

Reputation: 1 360

-11

PHP

echo '42';

Sorry, not sorry.

All you haters, this was meant to be sarcastic! But then again, sarcasm isn't allowed here.

geoff

Posted 12 years ago

Reputation: 107

So your answer got 3 downvotes and you deleted it :) I don't think this is a very creative option. – Cilan – 12 years ago

1Nope, that was about as uncreative as it gets. Challenge u to beat that. – geoff – 12 years ago