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

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 software in any programming language that takes approx 75 seconds to calculate, starting from wathever you want, the number 42 and which must print as output the solution.

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 and equivalent functions, be inventive

share|improve this question
6  
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); –  Josh Feb 4 at 21:04
27  
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... –  Fozzedout Feb 4 at 21:05
7  
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 –  Josh Feb 4 at 21:05
3  
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. –  Cruncher Feb 4 at 21:49
3  
I accidentally made mine take 10 minutes! :O –  Doorknob Feb 4 at 22:26

24 Answers 24

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

share|improve this answer
10  
So you'll either find a new number that satisfies this equation or you'll print 42 :) –  Assaf G. Feb 5 at 7:57
1  
@FezVrasta, because the last line went missing. doh! –  gnibbler Feb 5 at 8:10
2  
Wow! Perfect math rebus and the overclocking thing... ha ha ha +1! –  Tomas Feb 5 at 8:58
1  
it's funny that this answer has a hard cap score of 42 (not upvoting) –  pwned Feb 6 at 14:54
1  
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 –  agweber Feb 6 at 15:50

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.

share|improve this answer
1  
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 :( –  Fez Vrasta Feb 5 at 7:42
1  
@FezVrasta Sorry, I accidentally added some wrong code. Fixed it now, should work. –  Lego Stormtroopr Feb 5 at 7:49
4  
awesome, it works :) now we need a bigger computer to compute the question! –  Fez Vrasta Feb 5 at 7:53
8  
"I may be a sorry case, but I don't write jokes in base-13." - DNA –  mikeTheLiar Feb 5 at 15:09
3  
This is now sitting at 42 votes. Do I want more votes, or do I want the coolest possible score for this question? –  Lego Stormtroopr Feb 6 at 22:24

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
share|improve this answer
    
Looks like your Deep Thought has a different idea, it returns me 40 :P –  Fez Vrasta Feb 4 at 21:42
    
I've used Notepad++, I've a Windows 8 x64 –  Fez Vrasta Feb 4 at 21:55
    
No luck even with NotePad, the version with the exclamation mark instead works –  Fez Vrasta Feb 4 at 22:01
    
Cool, can you guess how it works? –  Yimin Rong Feb 4 at 22:02
2  
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 –  mynameiscoffey Feb 5 at 0:33

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"
share|improve this answer

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.
share|improve this answer

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;
}
share|improve this answer
5  
+1 for xkcd reference –  James Khoury Feb 5 at 7:12

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

share|improve this answer
1  
How do you ensure it lasts 75 seconds? –  Pierre Arlaud Feb 5 at 9:29
1  
@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. –  Doorknob Feb 5 at 12:47

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);
}
share|improve this answer
2  
while-looping until clock() exceeds some value seems to violate the no sleep() rule, since that's basically a cpu-intensive sleep –  mniip Feb 5 at 4:06
    
popularity-contest. –  Pierre Arlaud Feb 5 at 9:28
    
@ArlaudPierre It was code-golf when I submitted the answer. Anyways, it's fixed now. –  Oberon Feb 5 at 15:22

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

share|improve this answer

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;
}
share|improve this answer

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

share|improve this answer
1  
Much much more than 75 seconds... –  Fabinout Feb 5 at 14:57
    
but it's tottaly worth! –  rafaelcastrocouto Feb 6 at 11:06

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.

share|improve this answer

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
share|improve this answer

C# - 151 Characters

class P
{
   static void Main()
   {
      var w = new System.Diagnostics.Stopwatch();
      w.Start();
      while (w.ElapsedMilliseconds < 75000);
      System.Console.Write((int)'*');
   }
}
share|improve this answer
    
How is this not equivalent to thread sleep? –  valdetero Feb 5 at 17:44
    
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. –  Merin Nakarmi Feb 5 at 18:05
    
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. –  valdetero Feb 5 at 21:05
1  
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. –  microbian Feb 6 at 2:17

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.

share|improve this answer

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);
    }
}
share|improve this answer

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()
share|improve this answer

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.

share|improve this answer

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);
        }
    }
}
share|improve this answer
1  
you are using "sleep" –  Fez Vrasta Feb 5 at 22:29
    
oops, read it as can use sleep -10 for me! –  landers Feb 6 at 0:33

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

share|improve this answer

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.

share|improve this answer

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($=((_=_=>(_<<-~-~[])|-~[])(_(-~[])))<<-~[])",($=$=>$<<-~-~-~[]|-~[])((_=_=>_<<-~[]|-~[])(_(_(_($($($(-~[]))))))))^-~[])

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

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
share|improve this answer

I'm a little late, but here's my JavaScript example! It obviously might vary, but this seems to take around 73-75 seconds for me.

//We'll need to put all of our code into a callback function
var jqueryonload = function() {
    //The first thing we need to do is check and make sure all numbers between 0 and 312,500,000 are working properly
    //Standards are very clear about doing this
    for(i=0;i<=Math.pow(50,5);i++) {
        //A RegEx to check and make sure the number is a number
        if(/[.+]?\d+.*[\\+]?/.test(i)) {
        } else {
            //If it didn't work, we'll just try again
            location.reload();
        }
    }

    //Let's declare some useful variables - we'll use objects nested in arrays to properly comply with standards
    rands = [{
        foursix: "http://www.random.org/integers/?num=1&min=4&max=6&col=1&base=10&format=plain&rnd=new"
    }];
    PI=[{PI:Math.PI}];
    //Use random.org to get a random number between four and six
    $.get(rands[0].foursix, function(data) {
        //Loop indefinitely
        while(true) {
            //If the number is greater than one
            if(data>(5-4)) {
                //Reduce it by one
                data-=(5-4);
            //Once we have one
            } else {
                //Create an object nested inside an array with a value of one
                //Also, make sure it's an integer
                one=[{one:data*1}];
                //Stop looping
                break;
            }
        }
    }).success(function() { //Once we're finished with that
        //Loop eleven times
        for(i=0;i<=((one[0].one+"")+(one[0].one+""))*one[0].one;i++) {
            //Make sure booleans are still functional - just a failsafe
            if(true) {
                //A quick regular expression to skip the dot in pi
                if(/^\/?[]?.*[\d]*\.+.*?[...]*[\d+]?[a-zA-Z]*$/.test((PI[0].PI+"")[i])) { i++; }
                //If we haven't already defined the fortytwo variable, declare it
                if(typeof(fortytwo)=="undefined") {
                    //Two nested objects in an array - it's more secure this way. A little slower, but we all make sacrifices.
                    fortytwo=[{fortytwo:{fortytwo:0}}];
                } else {
                    //If we already did declare it, set it to itself just to be on the safe side.
                    fortytwo=fortytwo;
                }
                //More failsafes. Wouldn't want to try to access a variable that didn't exist.
                if(fortytwo[0] && PI[0]) {
                    //Access the i digit of pi and add it to our fortytwo variable
                    //Also multiply it by 1 to make sure it's an integer
                    fortytwo[0].fortytwo.fortytwo+=(PI[0].PI+"")[i]*one[0].one;
                }
            }
        }
        //Loop forty times
        for(i=0;i<=40;i++) {
            //A bunch more failsafes. This is important stuff.
            if(0.05 && fortytwo[0] && fortytwo[0].fortytwo && fortytwo[0].fortytwo.fortytwo) {
                //Subract 0.05 from the fortytwo variable
                fortytwo[0].fortytwo.fortytwo-=0.05;
            }
        }
        //Two more failsafes: one to make sure that our variable exists, and a simple RegEx to make sure it's a number
        if(fortytwo[0] && /^[\\]*[PI]?.+\.?\d+\d+[\/+]?[.]*$/.test(fortytwo[0].fortytwo.fortytwo)) {
            //Javascript isn't real good with decimals, so we round it down
            fortytwo[0].fortytwo.fortytwo=Math.floor(fortytwo[0].fortytwo.fortytwo);
        }
        //Make sure we can access the number one
        if(one[0].one) {
            //Increment the fortytwo variable by one because we rounded down
            fortytwo[0].fortytwo.fortytwo=fortytwo[0].fortytwo.fortytwo+1;
        }
        //Round it down again just to be sure
        fortytwo[0].fortytwo.fortytwo=Math.floor(fortytwo[0].fortytwo.fortytwo);



        console.log(fortytwo[0].fortytwo.fortytwo);
    });
}

//Now we'll load jquery dynamically, and run our actual code once it's finished
var head = document.getElementsByTagName('head')[(5-5)];
var script = document.createElement('script');
script.src = "http://code.jquery.com/jquery-1.11.0.js";
script.type = 'text/javascript';
script.onload = script.onreadystatechange = function() {
    if (script.readyState) {
        if (script.readyState === 'complete' || script.readyState === 'loaded') {
            script.onreadystatechange = null;                                                  
            jqueryonload();
        }
    } 
    else {
        jqueryonload();
    }
};
head.appendChild(script);

Here's a pastebin link to get the code coloring.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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