42
\$\begingroup\$

Introduction: Deep Thought calculated The answer to life the universe and everything in a period of 7.5 million years, the solution was 42.

Write a program in any programming language that takes approx 75 seconds to calculate, starting from whatever you want, and output the number 42.

N.B. The number 42 must be calculated somehow (random numbers, whatever you prefer), not just hard-coded in your script.

As suggested, you can't use sleep or equivalent functions. Be inventive.

\$\endgroup\$
18
  • 6
    \$\begingroup\$ This might better serve as a popularity contest to see what ways people can creatively come up with an answer rather than variations of sleep(75);print("%d\n",41+1); \$\endgroup\$
    – Josh
    Commented Feb 4, 2014 at 21:04
  • 30
    \$\begingroup\$ To calculate takes approx 75 seconds? But computer chips are so varied... How can this be possible - it might take 75 seconds on my machine, but the next computer might monster it in 7.5 seconds... \$\endgroup\$
    – Fozzedout
    Commented Feb 4, 2014 at 21:05
  • 7
    \$\begingroup\$ Without sleep available the answers are going to be very hardware dependent I imagine...what takes 75s on your machine will probably take 750s on my machine :P \$\endgroup\$
    – Josh
    Commented Feb 4, 2014 at 21:05
  • 3
    \$\begingroup\$ timeapi.org/utc/now. This seems like the best alternative to using sleep-like libraries of your language. All this takes is a few http requests. \$\endgroup\$
    – Cruncher
    Commented Feb 4, 2014 at 21:49
  • 3
    \$\begingroup\$ I accidentally made mine take 10 minutes! :O \$\endgroup\$
    – Doorknob
    Commented Feb 4, 2014 at 22:26

23 Answers 23

54
\$\begingroup\$

This takes about 75s on a raspberry pi overclocked to 1GHz

#!/usr/bin/env python
from itertools import product, count

for n in count(1):
    i = 0
    for a, b, c, d in product(range(n), repeat=4):
        if a > b > c > d > 0 == (a*b-c*d)%n == (a*c-b*d)%n == (a*d-b*c)%n:
            i += 1
    if i == n:
        break
print i

It works because:

42 is the only known value that is the number of sets of four distinct positive integers a,b,c,d, each less than the value itself, such that ab-cd, ac-bd, and ad-bc are each multiples of the value. Whether there are other values remains an open question

http://www.mathpages.com/home/kmath255.htm

\$\endgroup\$
8
  • 12
    \$\begingroup\$ So you'll either find a new number that satisfies this equation or you'll print 42 :) \$\endgroup\$
    – Assaf G.
    Commented Feb 5, 2014 at 7:57
  • 1
    \$\begingroup\$ @FezVrasta, because the last line went missing. doh! \$\endgroup\$
    – gnibbler
    Commented Feb 5, 2014 at 8:10
  • 2
    \$\begingroup\$ Wow! Perfect math rebus and the overclocking thing... ha ha ha +1! \$\endgroup\$
    – Tomas
    Commented Feb 5, 2014 at 8:58
  • 1
    \$\begingroup\$ it's funny that this answer has a hard cap score of 42 (not upvoting) \$\endgroup\$
    – pwned
    Commented Feb 6, 2014 at 14:54
  • 1
    \$\begingroup\$ I really want to upvote this because of the overlocked raspberry pi, but I just can't given it's current score. I have a bad feeling we're going to have a tie \$\endgroup\$
    – agweber
    Commented Feb 6, 2014 at 15:50
42
\$\begingroup\$

Python 2.7

To answer the question, one must know the question - and the question is:

What do you get when you multiply six by nine? Thanks to TRiG for the correction

So Deep Thought relies on the handy use of base 13:

613 x 913 = 4213

We import our constants:

from random import randrange as scrabbleBag, randint
from datetime import datetime,timedelta
life,universe,everything,nothing=6,9,1,-3
endOfTheUniverse = 80

We also define our earth-things, being a bag of scrabble tiles, Arthur (a predictable albeit it slightly odd, computer of sorts), Trillian (our rational heroine),

tile = lambda i: scrabbleBag(26)
arthur = lambda i: int(`i`,life+universe+everything+nothing)
trillian = lambda i: ''.join(map(str,divmod(i,life+universe+everything+nothing)))

We introduce Zaphod - a random sort, who eventually runs out of steam as we near the endOfTheUniverse.

zaphod = lambda : not(randint(0,(endOfTheUniverse-(datetime.now() - start).seconds)**3))

And Marvin the Paranoid Android, whose positive attitude could stop any party:

marvin = lambda : endOfTheUniverse<(datetime.now() - start).seconds

And we continue to run these 4 characters through the mix until they compute it:

while answer is not life * universe * everything:
  rack = sum(tile(i) for i in range(7))
  answer = (zaphod or marvin) and arthur(rack)
print trillian(answer)

The complete deepthought.py:

from random import randrange as scrabbleBag, randint
from datetime import datetime,timedelta
life,universe,everything,nothing=6,9,1,-3
endOfTheUniverse = 80

tile = lambda i: scrabbleBag(26)
arthur = lambda i: int(`i`,life+universe+everything+nothing)
trillian = lambda i: ''.join(map(str,divmod(i,life+universe+everything+nothing)))

start = datetime.now()

zaphod = lambda: not(randint(0,(endOfTheUniverse-(datetime.now() - start).seconds)**3))
marvin = lambda: endOfTheUniverse<(datetime.now() - start).seconds

answer = None
while answer is not life * universe * everything:
  rack = sum(tile(i) for i in range(7))
  answer = (zaphod() or marvin()) and arthur(rack)
print trillian(answer)

This should finish somewhere around the 75 second mark, definitely finishing by 80 seconds. Sometimes earlier to to Zaphods Infinite Improbability Drive.

\$\endgroup\$
10
  • 1
    \$\begingroup\$ the answer is great but if I run it on 2.7.2 it throws an error File "main.py", line 13, in zaphod = not(randint(i,(80-(datetime.now() - start).seconds)**3)) NameError: name 'i' is not defined :( \$\endgroup\$
    – Fez Vrasta
    Commented Feb 5, 2014 at 7:42
  • 1
    \$\begingroup\$ @FezVrasta Sorry, I accidentally added some wrong code. Fixed it now, should work. \$\endgroup\$
    – user8777
    Commented Feb 5, 2014 at 7:49
  • 4
    \$\begingroup\$ awesome, it works :) now we need a bigger computer to compute the question! \$\endgroup\$
    – Fez Vrasta
    Commented Feb 5, 2014 at 7:53
  • 8
    \$\begingroup\$ "I may be a sorry case, but I don't write jokes in base-13." - DNA \$\endgroup\$ Commented Feb 5, 2014 at 15:09
  • 3
    \$\begingroup\$ This is now sitting at 42 votes. Do I want more votes, or do I want the coolest possible score for this question? \$\endgroup\$
    – user8777
    Commented Feb 6, 2014 at 22:24
13
\$\begingroup\$

DOS Batch — the answer to life, the Universe and everything

Thanks to mynameiscoffey for his simplification!

Save as answer.bat:

@ ping 127.0.0.1 -n 76 >nul && @ echo %~z0

Then run it, and wait 75 seconds:

> answer
42
\$\endgroup\$
17
  • \$\begingroup\$ Looks like your Deep Thought has a different idea, it returns me 40 :P \$\endgroup\$
    – Fez Vrasta
    Commented Feb 4, 2014 at 21:42
  • \$\begingroup\$ I've used Notepad++, I've a Windows 8 x64 \$\endgroup\$
    – Fez Vrasta
    Commented Feb 4, 2014 at 21:55
  • \$\begingroup\$ No luck even with NotePad, the version with the exclamation mark instead works \$\endgroup\$
    – Fez Vrasta
    Commented Feb 4, 2014 at 22:01
  • \$\begingroup\$ Cool, can you guess how it works? \$\endgroup\$
    – user15259
    Commented Feb 4, 2014 at 22:02
  • 2
    \$\begingroup\$ why not just make it one line to avoid the messy CRLF issue, @ ping 127.0.0.1 -n 76 >nul && @ echo %~z0, using ` && ` instead of relying on a pair of CRLF \$\endgroup\$ Commented Feb 5, 2014 at 0:33
11
\$\begingroup\$

Bash (OS X)

This could probably be ported to other systems without too much trouble. Replace say with whatever you're using as a text-to-speech command line utility. The -f option takes input from a named file.

With a bit of luck, it might even output the correct number :-)

This takes almost exactly 1 minute 15 seconds to run on my system (OS X 10.5).

#!/bin/bash
grep -E '^life|universe|and.everything|[ultimate]question$' /usr/share/dict/words | sed 's/$/,/' | nl > "$TMPDIR/deepthought"
say -v Alex -f "$TMPDIR/deepthought"
nw=`cat $TMPDIR/deepthought | wc -l`
say -v Alex "The answer, to the ultimate question, is: $nw"
echo $nw
rm "$TMPDIR/deepthought"
\$\endgroup\$
10
\$\begingroup\$

MATLAB

This is a tough one. Since we do not really know the question, the only viable method of getting the answer is by means of a global optimisation method. In this case I opted for the simulated annealing method, since this one has given me nice answers to tough questions before.

All this code is doing is looking for the optimal value of a function which input is life itself. And the amazing thing is that it works. So, did I just validate Deep Thought?

tic;

the_answer=round(simulannealbnd(@(life)abs(3.7376696-log(life)),140489, ...
           -inf,inf,saoptimset('MaxFunEvals',10^16)))
toc;

Output:

the_answer =

    42

Elapsed time is 74.892428 seconds.
\$\endgroup\$
5
\$\begingroup\$

C - 1089 bytes

#include <time.h>
#include <stdio.h>

int answer(int the)
{
   int to = 0;

   while (the != 0) {
      to *= 10;
      to += the%10;
      the /= 10;
   }
   return to;
}

int optimism(int the)
{
    return abs(the);
}

int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

int main()
{
    // initialize
    int life = getRandomNumber(), universe, everything;

    // get inverse answer
    int question = clock();
    while (clock()-question < CLOCKS_PER_SEC*75) {
        life += getRandomNumber();
    }
    life = optimism(life); // optimism is the best way to see life
    life %= 1000;

    // avoids unwanted race conditions with the answer by "Lego Stormtroopr"
    if (life<100 || life>997) {life -= getRandomNumber()*100;}
    if (optimism(life/100%10 - life%10) < 2) {life += getRandomNumber();}
    universe = answer(life);
    everything = optimism(life<universe?life-universe:universe-life);

    printf("%d\n", (answer(everything)+everything+3)/26);

    return 0;
}

Compressed:

#include <time.h>

int f(int d) {
   int e = 0;
   while (d != 0) e = e*10+d%10, d /= 10;
   return e;
}

int main() {
    int a = 4, b, c, d = clock();
    while (clock()-d < CLOCKS_PER_SEC*75) a += 4;
    a = abs(a)%1000;
    a -= a<100||a>997?400:0;
    a += abs(a/100%10-a%10)<2?4:0;
    b = f(a);
    c = abs(a<b?a-b:b-a);
    return (f(c)+c+3)/26;
}
\$\endgroup\$
0
4
\$\begingroup\$

Ruby

t = Time.new.to_i
n = 0
loop{
  break if Random.new(n).rand(2000000) == Random.new(374076).rand(1000000)
  n += 1
}
puts Random.new(n).rand(2000000)
puts "Took #{Time.new.to_i - t} seconds; seed was #{n}"

Output on my machine:

42
Took 123 seconds; seed was 3771996

This abuses the RNG. ;)

\$\endgroup\$
3
  • 1
    \$\begingroup\$ How do you ensure it lasts 75 seconds? \$\endgroup\$ Commented Feb 5, 2014 at 9:29
  • 1
    \$\begingroup\$ @Arlaud It runs through 3.7 million iterations of a loop whIch generates 2 random numbers per iteration! Technically if you had some supercomputer it could be faster, but for any reasonable hardware it would take at least 75 secs, and I don't want to be boring and use sleep or time methods. \$\endgroup\$
    – Doorknob
    Commented Feb 5, 2014 at 12:47
  • \$\begingroup\$ Update: ... well now it prints Took 25 seconds; seed was 3771996 on my average-performance laptop. So, uhh... I lied. :P \$\endgroup\$
    – Doorknob
    Commented Jul 4, 2015 at 3:07
4
\$\begingroup\$

C

#include <stdio.h>
#include <time.h>

int i, j;

int main() {
    i = clock();
    while(clock() - i < 75 * CLOCKS_PER_SEC);
    for(i = j = 0 ; i < 48 ; i++)
        j += "The answer to Life, the Universe, and everything"[i];
    printf("%i", j % 157);
}
\$\endgroup\$
3
  • 2
    \$\begingroup\$ while-looping until clock() exceeds some value seems to violate the no sleep() rule, since that's basically a cpu-intensive sleep \$\endgroup\$
    – mniip
    Commented Feb 5, 2014 at 4:06
  • \$\begingroup\$ popularity-contest. \$\endgroup\$ Commented Feb 5, 2014 at 9:28
  • \$\begingroup\$ @ArlaudPierre It was code-golf when I submitted the answer. Anyways, it's fixed now. \$\endgroup\$
    – Oberon
    Commented Feb 5, 2014 at 15:22
4
\$\begingroup\$

JavaScript - Finding "the answer to life and everything" by solving an equation

Let's have a look at this equation :

1 / p  +  1 / q  +  1 / r  =  1 / 2

There is many solutions, but if you want r to be as big as possible and p, q and r to be naturals there is only two solutions :

1/3 + 1/7 + 1/42 = 1/2 and 1/7 + 1/3 + 1/42 = 1/2

with p <= q <= r, there is only one solution and r always equal to 42

What is the most (in)efficient way to solve a equation ?

By trying all possibles values !

Here is the code :

var n = Math.pow(2, 32); 
for (var i = 1; i <= n; i++)  
{ 
    for (var j = 1; j <= n;  j++)
    {
        for (var k = 1; k <= n; k++)
        {
            if ((1 / i + 1 / j + 1 / k) == 1 / 2)                
               throw k;                
        }
    }
}

How much time will it take ? To be honest, I do not know because I have not been able to run it to the end.

However, you can try with small n values (it has to be bigger or equal to 42) and you will get correct result. For small values such as n = 2000, it takes almost one minute on my laptop. So i guess with big values given in the example it will take days, weeks, or even years !!!

Finding the solution in approximately 75 seconds :

One requirement from initial question is it should take approximately 75 sec to execute. One way to achieve this is to automatically adjust the complexity of the algorithm over the time :

var now = new Date().getTime();
var iterations = 0; 
var n = Math.pow(2, 32); 
for (var i = 1; i <= n; i++)
{
    for (var j = 1; j <= n; j++)
    {
        for (var k = 1; k <= n; k++)
        {
            if ((1 / i + 1 / j + 1 / k) == 1 / 2)               
                throw k;
            
            if (new Date().getTime() - now > 1000) //one second has elapsed
            {
                now *= 2; //never wanna see you again
                n = 42;   //this is the minimum               
                while(3 * n * n + 7 * n + 42 < iterations * 74) n++;
                i = j = k = 0; //reset
            }
            iterations++;
        }
    }
}

How it works (for the curious) : it checks how many iterations have been done in one second, then multiply this by 74 and adjust n to match that value. eg : if it take one second to do 500 iterations, it will take 10 seconds to do 5000 iterations. Note that it multiply by 74 not 75 because we already spent one second for "benchmarking".

source and credits for math

\$\endgroup\$
2
\$\begingroup\$

C# - 151 Characters

class P
{
   static void Main()
   {
      var w = new System.Diagnostics.Stopwatch();
      w.Start();
      while (w.ElapsedMilliseconds < 75000);
      System.Console.Write((int)'*');
   }
}
\$\endgroup\$
4
  • \$\begingroup\$ How is this not equivalent to thread sleep? \$\endgroup\$
    – valdetero
    Commented Feb 5, 2014 at 17:44
  • \$\begingroup\$ Of course it is not equivalent to thread sleep. Thread sleep makes main thread inactive for specified amount of time. This program does not make main thread inactive. It involves main thread to compare elapsed time. And when that specified amount of time (75s) is elapsed, it prints the output. \$\endgroup\$ Commented Feb 5, 2014 at 18:05
  • \$\begingroup\$ I know <i>functionally</i> it is not the same, but follows the same premise. The OP wanted it to be creative and not have the the language wait 75 seconds - which is what this is doing. \$\endgroup\$
    – valdetero
    Commented Feb 5, 2014 at 21:05
  • 1
    \$\begingroup\$ To me this solution is as good/bad as the solution for DOS. The DOS solution is keeping the program busy by pinging, and this one is keeping itself busy by comparing the time elapsed. I don't see any difference. If that can get many upvotes so this one should also get. By the way, ping command does a 'sleep' internally. \$\endgroup\$
    – microbian
    Commented Feb 6, 2014 at 2:17
2
\$\begingroup\$

C++

Calculates the partitions of 10 via a rather inefficient method. Took 130s to run in a Release build on my system but someone with a sufficiently fast PC should be able to run it in ~75s...

#include <algorithm>
#include <iostream>
#include <numeric>
#include <set>
#include <vector>

using namespace std;

bool NextPermutationWithRepetition(vector<int>& perm, int n) {
    int carry = 1;
    auto it = begin(perm);
    while (it != end(perm) && carry) {
        ++*it;
        carry = (*it - 1) / n;
        *it = ((*it - 1) % n) + 1;
        ++it;
    }
    if (carry) {
        if (perm.size() == n) return false;
        perm.push_back(carry);
    }
    return true;
}

int main() {
    vector<int> perm;
    set<vector<int>> uniquePartitions;
    const int n = 10;
    while (NextPermutationWithRepetition(perm, n)) {
        if (accumulate(begin(perm), end(perm), 0) == n)  {
            auto sortedPerm = perm;
            sort(begin(sortedPerm), end(sortedPerm));
            uniquePartitions.insert(sortedPerm);
        }
    }
    cout << uniquePartitions.size() << endl;
}
\$\endgroup\$
2
\$\begingroup\$

Javascript

This will take a while to alert something ... but it's worth since it will show you The answer to life the universe and everything!

var x = 0, b = document.body.children[0];
var theAnswer = function(){
  b.textContent = ++x;
  if(x == 125774) alert(Math.pow(x, 1/Math.PI)).toFixed(0);  
  else setTimeout(theAnswer);
};
theAnswer();

Demo

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Much much more than 75 seconds... \$\endgroup\$
    – Fabinout
    Commented Feb 5, 2014 at 14:57
  • \$\begingroup\$ but it's tottaly worth! \$\endgroup\$
    – user15260
    Commented Feb 6, 2014 at 11:06
2
\$\begingroup\$

Python

Sometimes an answer is only clear at the very end of a calculation, but aspects of it are visible before termination.

And little known is the sequence of inputs Deep Thought was seeded with:

271, 329, 322, 488, 79, 15, 60, 1, 9

Hence:

from datetime import datetime
n = datetime.now
o = n().second

def bs(x,n,t,f):
    return ([t]+bs(x-2**(n-1),n-1,t,f) if x>=2**(n-1) else [f]+bs(x,n-1,t,f)) if n>0 else []

u = [271,329,322,488,79,15,60,1,9,'#',' ','',]
for i, g in enumerate(u[:5]):
    while n().second!=(o+(i+u[7])*u[5])%u[6]:
        pass # the dice
    print u[11].join(bs(g,*u[8:11]))

Et voila - the answer is provided after 75 seconds.

\$\endgroup\$
2
\$\begingroup\$

Assembly (linked by gcc)

On a sufficiently slow computer (CPU speed ~2Hz) this should take around 75 seconds to run:

  .globl        main
main:
  movl  $52, %edx
  movl  $0, %edi
l4:
  addl $1, %edi
  cmp %edx, %edi
  jl l4
  call  putchar
  movl  $50, %edx
  movl  $0, %edi
l2:
  addl $1, %edi
  cmp %edx, %edi
  jl l2
  call  putchar
  movl  $10, %edx
  movl  $0, %edi
ln:
  addl $1, %edi
  cmp %edx, %edi
  jl ln
  call  putchar
  ret
\$\endgroup\$
1
\$\begingroup\$

Bash and Linux utils:

#!/bin/bash

if [ $(uname) == "Linux" ]; then
    : $(arecord -q | head -c 600000)
    man -s4 random | head -n1 | tr -d ' ' | wc -c
else
    echo "Deep Thought didn't run $(uname)"
fi

Deep Thought is listening carefully all the way through the calculation.

\$\endgroup\$
1
\$\begingroup\$

Java (227 characters)

Who says that bitwise manipulations are not fun? Or that java can't be confusing?
We loop for 75 seconds and then boom the answer.

public class T{public static void main(String[]b){long d=(1<<16^1<<13^1<<10^31<<3);long t=System.currentTimeMillis();long e=t+d;for(;e>System.currentTimeMillis();){}d=d%((((d&~(1<<16))>>7)^(1<<4))^1<<2);System.out.println(d);}}

Ungolfed

public class T
{
    public static void main(String[] b)
    {
        long d = (1 << 16 ^ 1 << 13 ^ 1 << 10 ^ 31 << 3);
        long t = System.currentTimeMillis();
        long e = t + d;
        for (; e > System.currentTimeMillis();){}
        d = d % ((((d & ~(1 << 16)) >> 7) ^ (1 << 4)) ^ 1 << 2);
        System.out.println(d);
    }
}
\$\endgroup\$
0
\$\begingroup\$

PureBasic

In keeping with the fact that different hardware will produce different results, there is no fixed answer for this. I am using an elapsed time function so I know when to stop calculating.

Basically, it will calculate the largest two prime numbers when subtracted is 42

Faster your machine, the larger the primes will be :-)

OpenConsole()

sw = ElapsedMilliseconds()
FoundFigure1 = 0
FoundFigure2 = 0

PreviousPrime = 1

For i = 3 To 10000000000 Step 2
  PrimeFound = #True
  For j = 2 To i-1
    If i % j = 0
      PrimeFound = #False
      Break
    EndIf
  Next
  If PrimeFound = #True
    If i - PreviousPrime = 41+1
      FoundFigure1 = PreviousPrime
      FoundFigure2 = i
    EndIf

    PreviousPrime = i
  EndIf

  If ElapsedMilliseconds() - sw > 75000
    Break
  EndIf
Next

Print("Answer: ")
Print(Str(FoundFigure2 - FoundFigure1))
Input()
\$\endgroup\$
0
\$\begingroup\$

MeatSpace

Pace off a distance which takes approximately 70/4 seconds for your servant^H^H^H^Hcomputer (it could be human, dog, or anything that can pick up numeral tiles) to walk. Place a large numeral 4 and a large numeral 2 there. Place your computer to the output point. Start the timer, have it walk to the numeral depot and bring back one number at a time.

I allocated 5 seconds to pick them up and put them down.

\$\endgroup\$
0
\$\begingroup\$

Another C# Example

using System;
using System.Threading;

namespace FourtyTwo
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime then = DateTime.Now;
            Thread.Sleep(42000);
            DateTime now = DateTime.Now;
            TimeSpan t = now - then;
            Console.WriteLine(t.Seconds);
        }
    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ you are using "sleep" \$\endgroup\$
    – Fez Vrasta
    Commented Feb 5, 2014 at 22:29
  • \$\begingroup\$ oops, read it as can use sleep -10 for me! \$\endgroup\$
    – landers
    Commented Feb 6, 2014 at 0:33
0
\$\begingroup\$

Ruby

A program to add (0.56) power n for 75 times. Value of n is 1

Where n=1 should be obtained from any form of Time diffrence

def solve
  a=0.56
  i=0
  t1=Time.now
  while(i < 75)
        t1 = Time.now
        while((b=Time.now-t1) < 1.0)
        end
        a += 0.56 ** b.to_i
        i += 1
  end
  a.to_i
end

puts solve

Using ruby time difference I've verified the execution time which is approx 75.014267762

\$\endgroup\$
0
\$\begingroup\$

PHP

<?php
set_time_limit(80);
ini_set('max_execution_time', 80);
//$start=time();
$count=0;
do{
$rand=rand(0,(75000000/40+2));  
$rand=rand(0,$rand);
    if(($rand==42 || $rand==75-42 || $rand== floor(75/42)) && (!rand(0,(4*2)))
      ){
      $count++;
    }
}while($count!=42);
echo $count;
//echo '<br>elapsed time is '.(time()-$start);
?>

This is as close as I'm getting tonight. Running it at tecbrat.com, an old IBM NetVista P4 running Ubuntu 10.04, showed 69 seconds and 78 seconds on my last 2 runs.

\$\endgroup\$
0
\$\begingroup\$

JavaScript (Bitwise obfuscation) (not bad for 136 bytes!)

It may be seen as a bit on the cheaty side, but the functions were meticulously thought out, bearing in mind that the 75000ms value would be calculated prior to the functions used to calculate 42. It's quite poetic when you look at it, really :)

setTimeout("alert($=((_=_=>(_<<-~-~[])|-~[])(_(-~[])))<<-~[])",($=$=>$<<-~-~-~[]|-~[])((_=_=>_<<-~[]|-~[])(_(_(_($($($(-~[]))))))))^-~[])

\$\endgroup\$
5
  • \$\begingroup\$ I'm getting a syntax error... Unexpected token > \$\endgroup\$
    – user15260
    Commented Feb 11, 2014 at 11:41
  • \$\begingroup\$ I have this working on Firefox 26.0 which accepts the x=x=>f(x) notation... What version are you running this on? \$\endgroup\$ Commented Feb 12, 2014 at 23:25
  • \$\begingroup\$ i'm running chrome 31 on windows 7 ... \$\endgroup\$
    – user15260
    Commented Feb 13, 2014 at 12:11
  • 1
    \$\begingroup\$ @rafaelcastrocouto Ah, sadly fat arrow notation used to define the two functions in each of the statements only works for Firefox 22 and above... \$\endgroup\$ Commented Feb 20, 2014 at 10:31
  • \$\begingroup\$ i'm almost crying ... your solution is indeed beautyful! \$\endgroup\$
    – user15260
    Commented Feb 21, 2014 at 11:20
0
\$\begingroup\$

I am not too good with this kind of stuff. I'm an app developer but I've never had any training in C and I mostly make apps that grab stuff from servers and make the information look pretty...

I have no idea if this will work and there's a bit of extra code in there because it's in a iphone app and I display a progress hud and an alert view when 42 has been reached:

#import "ViewController.h"
#import "MBProgressHUD.h"

@interface ViewController ()

@property (nonatomic, retain) MBProgressHUD * hud;

-(IBAction)answer:(id)sender;

@end

int number;
int initialCounter;

@implementation ViewController
@synthesize hud;

-(IBAction)answer:(id)sender
{
    hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText = @"Calculating";

    [self calculate];

    number = arc4random();
}

-(void)calculate
{

    int random = arc4random();

    if (number == 42){
        hud.hidden = YES;
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Complete!"
                                                          message:@"The answer is 42."
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];

        [message show];
    }

    else if(number<42){
        number = number + random;
        dispatch_async(dispatch_get_main_queue(), ^{
             [self calculate];
        });
    }

    else if(number>42){
        number = number - random;
        dispatch_async(dispatch_get_main_queue(), ^{
             [self calculate];
        });
    }
}

@end
\$\endgroup\$

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