text:
QR Codes... and all that Jazz!
This is going to be relatively challenging code-golf challenge.
Input: Any URL, must have the protocol attached, e.g. http://codegolf.stackexchange.com (which will be our test case)
Output: A generated QR Code that represents this URL, which, when scanned by a smart device will take you to that URL on the smart device's browser.
Rules for this Code-Golf

As usual, smallest code wins.
No external web resources, libraries or plugins to generate the code for you. Your code must calculate the QR code image.
Output can be presented by an image, generated by HTML5/CSS3, or even using appropriate Unicode blocks, or if your platform's ASCII has it available, through ASCII characters that can form the QR code (this last one is directed at Commodore 64 Basic, Amiga QBasic, Amstrad Basic, etc users), but it must generate a QR code output such that I can scan the code.
Entries of the code must be followed with the generated output, either by a screen shot of the output after executing your code, or with a link showing the output (whichever suits the situation best)
You are to test your code with the URL "http://codegolf.stackexchange.com", and report the output in accordance to Rules 3 to 4.
You are to also test your code with a URL of your choice, and report the output in accordance to Rules 3 to 4.

References:
1) http://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders
2) http://www.pclviewer.com/rs2/calculator.html
3) http://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction
4) http://en.wikipedia.org/wiki/QR_code
5) http://www.qrstuff.com/ for inspiration... ;)

Infinite recursion at rule 5.

@ace Well spotted... this has been fixed

After reading some documentation, I think "relatively challenging" is an understatement.

Can we get a clarification as to what "your code must calculate the QR code image" means?  I'm taking it to mean that we must do the two major points in the submitted code: 1) RS encoding, and 2) module layout.

rule 3: so is ascii art printed from a terminal fine, or does it have to go into an actual image file?

also, which of the QR code specifications do we use? how much error correction?

@professorfish ASCII art... hmmm... If you can pull it off then by all means try it... Also the QR specification to be used is whatever works to your advantage... This is code golf, after all...

Mathematica: 20B ;) #~BarcodeImage~"QR"&

@hYPotenuser This is almost the same as a previously deleted answer, deleted because it was a built-in function within the language.

Python 3: 974 chars [nb]
Further beat with the ugly stick, see notebook on GH-Gist. Python 3 has built-in ASCII-85 encoding, which helps with the zipped saus. 3's more advanced built-in compression algorithms (LZMA) don't seem to work well with such small things.
Zipping is very fickle about changing characters around, was almost tempted to write something that would randomly try different 1-letter names for variables to minimize the zipped size.
Python 2: 1420 1356 1085 1077 characters

I read the first argument passed when called, which can be a string up to 106-ish characters long. The output is always a version 5-L QR code and mask 4 which means it's 37x37 modules large and can only handle ~5% damage.
The program's only dependencies are numpy (array manipulations) and matplotlib (display only); all Reed-Solomon encoding, data packing, and module layout is handled within the provided code.  For RS, I basically robbed the Wikiversity functions...it's still kind of a black-box for me.  Learned a ton about QR in any event.
Here's the code before I beat it with the ugly stick:
import sys
import numpy as np
import matplotlib.pyplot as plt
# version 5-L ! = 108 data code words (bytes), 106 after metadata/packing

### RS code stolen from https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#RS_generator_polynomial
gf_exp = [1] + [0] * 511
gf_log = [0] * 256
x = 1
for i in range(1,255):
    x <<= 1
    if x & 0x100:
        x ^= 0x11d
    gf_exp[i] = x
    gf_log[x] = i
for i in range(255,512):
    gf_exp[i] = gf_exp[i-255]

def gf_mul(x,y):
    if x==0 or y==0:
        return 0
    return gf_exp[gf_log[x] + gf_log[y]]

def main():
    s = sys.argv[1]

    version = 5
    mode = 4 # byte mode
    dim = 17 + 4 * version
    datamatrix = 0.5 * np.ones((dim, dim))
    nsym = 26

    # PACK
    msg = [mode * 16, len(s) * 16] + [ord(c) << 4 for c in s]
    for i in range(1, len(msg)):
        msg[i-1] += msg[i] // 256
        msg[i] = msg[i] % 256

    pad = [236, 17]
    msg = (msg + pad * 54)[:108]

    # MAGIC (encoding)
    gen = [1]
    for i in range(0, nsym):
        q = [1, gf_exp[i]]
        r = [0] * (len(gen)+len(q)-1)
        for j in range(0, len(q)):
            for i in range(0, len(gen)):
                r[i+j] ^= gf_mul(gen[i], q[j])
        gen = r
    msg_enc = [0] * (len(msg) + nsym)
    for i in range(0, len(msg)):
        msg_enc[i] = msg[i]
    for i in range(0, len(msg)):
        coef = msg_enc[i]
        if coef != 0:
            for j in range(0, len(gen)):
                msg_enc[i+j] ^= gf_mul(gen[j], coef)
    for i in range(0, len(msg)):
        msg_enc[i] = msg[i]

    # PATTERN
    # position marks
    for _ in range(3):
        datamatrix = np.rot90(datamatrix)
        for i in range(4):
            datamatrix[max(0, i-1):8-i, max(0, i-1):8-i] = i%2
    datamatrix = np.rot90(datamatrix.T)

    # alignment
    for i in range(3):
        datamatrix[28+i:33-i, 28+i:33-i] = (i+1)%2

    # timing
    for i in range(7, dim-7):
        datamatrix[i, 6] = datamatrix[6, i] = (i+1)%2

    # the "dark module"
    datamatrix[dim-8, 8] = 1

    # FORMAT INFO
    L4 = '110011000101111' # Low/Mask4
    ptr_ul = np.array([8, -1])
    steps_ul = [0, 1] * 8 + [-1, 0] * 7
    steps_ul[13] = 2 # hop over vertical timing
    steps_ul[18] = -2 # then horizontal

    ptr_x = np.array([dim, 8])
    steps_x = [-1, 0] * 7 + [15-dim, dim-16] + [0, 1] * 7

    for bit, step_ul, step_x in zip(L4, np.array(steps_ul).reshape(-1,2), np.array(steps_x).reshape(-1,2)):
        ptr_ul += step_ul
        ptr_x += step_x
        datamatrix[tuple(ptr_ul)] = int(bit)
        datamatrix[tuple(ptr_x)] = int(bit)

    # FILL
    dmask = datamatrix == 0.5

    cols = (dim-1)/2
    cursor = np.array([dim-1, dim]) # starting off the matrix
    up_col = [-1, 1, 0, -1] * dim
    down_col = [1, 1, 0, -1] * dim
    steps = ([0, -1] + up_col[2:] + [0, -1] + down_col[2:]) * (cols/2)
    steps = np.array(steps).reshape(-1, 2)
    steps = iter(steps)

    # bit-ify everything
    msg_enc = ''.join('{:08b}'.format(x) for x in msg_enc) + '0' * 7 # 7 0's are for padding
    for bit in msg_enc:
        collision = 'maybe'
        while collision:
            cursor += steps.next()
            # skip vertical timing
            if cursor[1] == 6:
                cursor[1] = 5
            collision = not dmask[tuple(cursor)]
        datamatrix[tuple(cursor)] = int(bit)

    # COOK
    mask4 = lambda i, j: (i//2 + j//3)%2 == 0
    for i in range(dim):
        for j in range(dim):
            if dmask[i, j]:
                datamatrix[i, j] = int(datamatrix[i, j]) ^ (1 if mask4(i, j) else 0)

    # THE PRESTIGE
    plt.figure(facecolor='white')
    plt.imshow(datamatrix, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.axis('off')
    plt.show()

if __name__ == '__main__':
    main()

After:
import sys
from pylab import*
n=range
l=len
E=[1]+[0]*511
L=[0]*256
x=1
for i in n(1,255):
 x<<=1
 if x&256:x^=285
 E[i]=x;L[x]=i
for i in n(255,512):E[i]=E[i-255]
def f(x,y):
 if x*y==0:return 0
 return E[L[x]+L[y]]
m=sys.argv[1]
m=[ord(c)*16 for c in'\4'+chr(l(m))+m]
for i in n(1,l(m)):m[i-1]+=m[i]/256;m[i]=m[i]%256
m=(m+[236,17]*54)[:108]
g=[1]
for i in n(26):
 q=[1,E[i]]
 r=[0]*(l(g)+l(q)-1)
 for j in n(l(q)):
    for i in n(l(g)):r[i+j]^=f(g[i],q[j])
 g=r
e=[0]*134
for i in n(108):
 e[i]=m[i]
for i in n(108):
 c=e[i]
 if c:
    for j in n(l(g)):e[i+j]^=f(g[j],c)
for i in n(108):e[i]=m[i]
m=.1*ones((37,)*2)
for _ in n(3):
 m=rot90(m)
 for i in n(4):m[max(0,i-1):8-i,max(0,i-1):8-i]=i%2
m=rot90(m.T)
for i in n(3):m[28+i:33-i,28+i:33-i]=(i+1)%2
for i in n(7,30):m[i,6]=m[6,i]=(i+1)%2
m[29,8]=1
a=array
t=tuple
g=int
r=lambda x:iter(a(x).reshape(-1,2))
p=a([8,-1])
s=[0,1]*8+[-1,0]*7
s[13]=2
s[18]=-2
P=a([37,8])
S=[-1,0]*7+[-22,21]+[0,1]*7
for b,q,Q in zip(bin(32170)[2:],r(s),r(S)):p+=q;P+=Q;m[t(p)]=g(b);m[t(P)]=g(b)
D=m==0.1
c=a([36,37])
s=r(([0,-1]+([-1,1,0,-1]*37)[2:]+[0,-1]+([1,1,0,-1]*37)[2:])*9)
for b in ''.join('{:08b}'.format(x) for x in e):
 k=3
 while k:
    c+=s.next()
    if c[1]==6:c[1]=5
    k=not D[t(c)]
 m[t(c)]=g(b)
a=n(37)
for i in a:
 for j in a:
    if D[i,j]:m[i,j]=g(m[i,j])^(j%3==0)
imshow(m,cmap=cm.gray_r);show()

(relying on a tab to count as 4/8/whatever number of spaces >= 2., not sure how well it will copy)
Because it's so long, we can zip it (saw someone do this somewhere else, forgot who though :( ) to save some more characters, bringing the total down to 1085 1077 because pylab is filthy:
import zlib,base64
exec zlib.decompress(base64.b64decode('eJxtU0tzmzAQvvSkX6FLaglkyiM2hHRvyS2HZNobo3QwwY6IBVjQFrfT/96V3KR4Wg5I+/6+3ZXSfWdGOhwHsjWdpv1xX26oclqPtGDKdleTPezrltxCEUm/CKW3iiJyB/YWr9ZkgohsO0MVVS1tWSTi1YrnhE4fP6KFqi2d3qNfPj1CnK0IvS2UhOn6rpgkqHkkxolVFPPceeBviRpJnuot3bJJHG1Sm807AoS5qcevpqUhoX9ut4VN6d8VRymJBuQUlGb3DUGjVHTmiVXci9bUVqyw4uLdwq+eDdszzbmv5TkJp801gkDSgKf8gCSu7cVJF5a6Bqb9Ik7WIkqxLZe8yKMwk2RnW3VGbW3BH1AtLDmJoF3/sPiO+3t24MuIEwetOUVYnY3Bb5bHuvPcFMpv5CNs2Q6TiUPRSAzegSG1yxoll2dkwsxmql+h/8dWgbW69lY5favazKvWs6qNFBX/J8/fChqCyOvaemAsSQX34pPzl5NzYktqMN14FWKbyZzhpW26LicWCmw9z7OlEucibs1FTN7Cg89nQBIbH2e+ypMEQ99uEpjyI46RM+dUJKEbslhb4Gsxc8MsVyKTuMIllMaURzLC+LXf1zhd1Y7EwL7Um6eSTrkaa8NKNvHA1MNz2ddsia+Ac9JDyYpM4ApxMuBoRCS9zC/QilNKyVBEiYTYnlhoGZN7648Ny9D/E7z6YUAci9g9PpshdRQ24iAeLI0fqmcbhczjKA15EedSGDZw/H3CqfU+HK7vfXjA1R1ZzyXs2IY74f6PQG5A44sKIlK5+muRpA6wYQwr2gfALBZEYwUvSV0V/832j4l7V6ehbCzAxSJoOgS4+JmH2ebXIkCLLkfslxv8ZH1quxIvkBD6/Vnta/pyWv3KhyFo62lk3Ml2P/FpAaxzd66c9gXabqQ3SKniuMT6dDlxKwE7k85WpMxn76zMX9Pe4BI00u1CY0NPF/7ImosEm8OJ0sNz951pUemyh0oHO9yJL4ZfOzX/DQ2mdSs='))

If you replace the last line with the following (it adds 62 chars), you get nearly-perfect output, but the other still scans, so whatever.
figure(facecolor='white');imshow(m,cmap=cm.gray_r,interpolation='nearest');axis('off');show()

Great job! It's a pity that Python isn't the best in golfing solutions, but this is remarkable coding, @NickT!

I could probably save some more if I lose the struct call and some unnecessary bit pushing by just truncating my 'master string'...

FYI the second indentation level can be just two spaces. I've noticed that you use four/tab.

@BetaDecay it's supposed to just be 1 tab (1 tab > 1 space as far as indenting is concerned...I think SE breaks tabs?)

@NickT yeah, it does.

There's a decent saving to be made (if it survives the compression) by replacing the implementation of gf_mul with a long multiplication. You can ditch the tables entirely; the multiplication is def f(x,y):\n r=0\n for _ in n(8):\n\tif y&1:r^=x\n\tx,y=x*2,y//2\n\tif x&256:x^=285\n return r and to get round the usage of gf_exp in the second loop of main you have to pull out an accumulator: E=1\nfor i in n(26):\n q=[1,E]\n E=f(E,2)\n ... I make it a saving of 75 bytes (5.6%) before compression.

In fact, the calculation of gen can also be golfed quite a lot: g=[1]+[0]*26\nE=1\nfor i in n(26):\n for j in n(26,0,-1):\n\tg[j]^=f(g[j-1],E)\n\tE=f(E,2)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Interactive Lights Off game
Intro
I guess most people are familiar with the game Lights Off, but in case someone isn't, here is a short description:

You start with an NxN grid where each cell in the grid is a light. For this example N=5. There are 2 ways the game can start: either all of the lights are on, or some lights are off. The goal is to turn off all of the lights. If you toggle a light, the lights left, right, above and below it will toggle with it.

All Lights on
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O

Toggled cells
Toggled(0,0) | Toggled(1,2)| Toggled(2,4)
X X O O O    |  O O X O O  |  O O O O O
X O O O O    |  O X X X O  |  O O O O X
O O O O O    |  O O X O O  |  O O O X X
O O O O O    |  O O O O O  |  O O O O X
O O O O O    |  O O O O O  |  O O O O O

Task
Make an interactive game of Lights Off with as little code as possible.
Requirements
There is a setup phase and a play phase.
The setup phase takes user input to determine the grid size (minimum size of 5) and whether the grid starts with all of the lights on. If the grid should not start with all of the lights on, lights must be selected randomly to start off: at least 1 and at most 20% of the lights.
In the play phase, the grid is displayed to the user and moves are taken as input. The application could use a windowed GUI with lights toggled by clicking, or a text UI which takes typed input of the coordinates of the cell to toggle.
When the user reaches a solved state (all lights off), the application must notify them that they have solved the puzzle, and show how many moves it took.
The use of external resources is not allowed.
If there is anything unclear or missing please let me know :)
Related questions

Lights Out - Find the solution asks for a computer-generated solution given the input
Lights Off! is more similar to this one, but non-interactive

Can you justify why this isn't a duplicate of question 1? Do the answers there demonstrably not find the shortest solution?

Question 1 requires the input of a full grid where the program will find the solution for you, where in this question the program will create a grid for the user to solve.

do we need to generate a solvable puzzle? Does every puzzle need to be possible to generate? If the size is 2x2, do we really need to start in the solved state?

If the interesting bit is unchanged and the new bit is as trivial as that, I don't think it adds value to the site.

@JanDvorak the minimum size is 5x5

@PeterTaylor which is the interesting bit? Finding the solution is not required here.

@JanDvorak, "User will be notified if the puzzle is solved and shown how much moves it took."

@PeterTaylor we're tracking the user's moves here, not the shortest solution. Also, verifying a position is solved is not the same as finding a solution.

@PeterTaylor The interesting part (in my opinion) is creating a playable game, generating the grid, adjusting the grid according to the players moves and checking the puzzle for completion with as little code as possible. I will edit the question to make it more clear that the player will be in control.

@JanDvorak If it were we'd have P=NP :)

APL (101)
00{⎕←'XO'[1+⍵]⋄1∨.=,⍵:(⍺+1)∇⍵≠(⍳⍴⍵)∊⎕∘+¨Z,⌽¨Z←0∘.,¯1 0 1⋄'SOLVED',⍺}⎕{⍺:⍵ ⍵⍴1⋄~(⍵ ⍵⍴⍳V)∊V?⍨⌊.2×V←⍵*2}⎕

The first input is the size, the second input is the start value (0=some off, 1=on). Coordinates are 1-based.
      0{⎕←'XO'[1+⍵]⋄1∨.=,⍵:(⍺+1)∇⍵≠(⍳⍴⍵)∊⎕∘+¨Z,⌽¨Z←0∘.,¯1 0 1⋄'SOLVED',⍺}⎕{⍺:⍵ ⍵⍴1⋄~(⍵ ⍵⍴⍳V)∊V?⍨⌊.2×V←⍵*2}⎕
⎕:
      5
⎕:
      1
OOOOO
OOOOO
OOOOO
OOOOO
OOOOO
⎕:
      2 2
OXOOO
XXXOO
OXOOO
OOOOO
OOOOO
⎕:

C++, 564 bytes
#include <iostream>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;int main(){int n,p,s=0,y,i=0,b;cin>>n>>b;if(n<5)n=5;vector<int>m(n*n,1);srand(time(0));if(b)for(int&c:m)c=rand()<RAND_MAX/6;for(;i<n*n;i++)cout<<m[i]<<(-~i%n?"":"\n");while(find(m.begin(),m.end(),1)!=m.end()){cin>>p>>y;p+=y*n;if(p<0||p>=n*n)continue;m[p]=!m[p];if(p%n)m[p-1]=!m[p-1];if(p%n+1<n)m[p+1]=!m[p+1];if(p>=n)m[p-n]=!m[p-n];if(p+n<n*n)m[p+n]=!m[p+n];for(i=0;i<n*n;i++)cout<<m[i]<<(-~i%n?"":"\n");s++;}cout<<"Solved in "<<s<<" steps."<<endl;}

In setup phase, the user should input the grid size first. Then if the grid should starts with all of the lights on, the user should input 0; otherwise 1.
In play phase, the user should input the 0-based coordinates of the cell to toggle until all lights off.
Original code:
#include <iostream>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
int main() {
    int n, p, s = 0, y, i = 0, b;
    cin >> n >> b;
    if(n < 5) n = 5;
    vector<int> m(n * n, 1);
    srand(time(0));
    if (b) for (int& c : m) c = rand() < RAND_MAX / 6;
    for (; i < n * n; i++) cout << m[i] << (-~i % n ? "" : "\n");
    while (find(m.begin(), m.end(), 1) != m.end()) {
        cin >> p >> y;
        p += y * n;
        if (p < 0 || p >= n * n) continue;
        m[p] = !m[p];
        if (p % n) m[p - 1] = !m[p - 1];
        if (p % n + 1 < n) m[p + 1] = !m[p + 1];
        if (p >= n) m[p - n] = !m[p - n];
        if (p + n < n * n) m[p + n] = !m[p + n];
        for (i = 0; i < n * n; i++) cout << m[i] << (-~i % n ? "" : "\n");
        s++;
    }
    cout << "Solved in " << s << " steps." << endl;
}

Nice answer.  You can save a few characters by dropping the #include <ctime> and initializing your random number generator with the address of one of your locals; ex srand(&n);.  That should be random enough to produce good results.

@Josh &n is fixed on my machine. srand((int)&m[0]); is better but I think it is implementation-defined.

What if you declared your variables at global scope?  Would that add any randomness in to their addresses?

@Josh Unfortunately, no.

C - 365 characters
#define a for(y=0;y<w*w;y++)
*k,i,w,x,y,c=0;main(){scanf("%i %i",&w,&i);k=malloc(4*w*w+8*w)+4*w;i&=1;srand(k);a k[y]=i||ra
nd()<6553;i^=1;for(;;){x=0;a{putchar(k[y]?79:88);x|=k[y]!=i;!((y+1)%w)&&putchar(10);}if(!x&&c
)return printf("won in %i",c);putchar(62);scanf("%i %i",&x,&y);k[x*w-w+y]^=x>0;k[x*w+y-1]^=y>
0;k[x*w+w+y]^=x<w-1;k[x*w+y+1]^=y<w-1;k[x*w+y]^=1;c++;}}

In setup phase, it asks the user for two integers: table size and starting state (0 for off and 1 for on), respectively.
After that, before every move, it will print the grid, then prompt (>) the user for 0-based xy coordinates of the point.

This is beautiful.  You blew the C answer I was working on out of the water.  I did notice that your solution seems to segafault on input 0 0 due to the code k[x*w+y-1].

Additionally, as per the spec, if the user specifies 'lights off', there is supposed to be at least one light randomly turned on.

The random part should work. Not sure about your segfault, @Josh, so I added two lines in the grid memory. What OS and compiler are you using? It isn't segfaulting on W7x64.

an input of n, (a number followed by a comma) causes it to go into infinite loop.

@B1KMusic Coordinates are separated by whitespace, not a comma.

@Oberon I know. I just thought it was an interesting thing to point out.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Determine whether a car can get around a route with a limited amount of gas
Using any programming language that supports functions, have the function
is_enough(strArr)

that take strArr which will be an an array consisting of the following elements:

N which will be the number of gas stations in a circular route
and each subsequent element will be the string g:c where

g is the amount of gas in gallons at that gas station and
c will be the amount of gallons of gas needed to get to the following gas station.

For example strArr may be:
["4","3:1","2:2","1:2","0:1"].

Your goal is to return the index of the starting gas station that will allow you to travel around the whole route once, otherwise return the string "impossible".
For the example above there are 4 gas stations, and your program should return the string "1" because:

Starting at station 1 you receive 3 gallons of gas and spend 1 getting to the next station.
Then you have 2 gallons + 2 more at the next station and you spend 2 so you have 2 gallons when you get to the 3rd station.
You then have 3 but you spend 2 getting to the final station,
At the final station you receive 0 gallons and you spend your final gallon getting to your starting point.

Starting at any other gas station would make getting around the route impossible, so the answer is "1".
If there are multiple gas stations that are possible to start at, return the smallest index (of the gas station). N will be >= 2.
Correct Sample Outputs:
Input: ["4","1:1","2:2","1:2","0:1"]
Output: "impossible"

Input: ["4","0:1","2:2","1:2","3:1"]
Output: "4"

The winner will be the one to use the shortest code although it will be long.

What's the objective winning criterion? I'm voting to close because there's no way to tell who the winner is.

Just put a code-golf tag on it and it'll be ok.

Voting to close just because of a missing tag is a bit draconian, wouldn’t you say? Just add the tag.

Are there always precisely N+1 elements in strArr?  This would make N redundant in case the language already provides a way of getting the length of the array, right? (it'd still be useful for e.g. C though.)

Two of the answers are interpreting the spec as requiring the name is_enough (9 chars); three are using a single-char name, and one doesn't name the function at all. Could you please clarify what is permissible?

Bash 178 170 161 157
Rather straight forward.
is_enough(){((t=(n=$1-1)<0))&&echo impossible||(x=(n ${@:3} $2);for z in ${@:2};do(((t+=${z%:*}-${z#*:})<0))&&is_enough ${x[*]}&&return;done;echo $[$#-++n])}

Spaced out:
is_enough() {
     ((t=(n=$1-1)<0)) && echo impossible || (
         x=(n ${@:3} $2);
         for z in ${@:2};do
             (((t+=${z%:*}-${z#*:})<0)) && is_enough ${x[*]} && return;
         done;
         echo $[$#-++n]
     )
}

Ruby, 111
Here's a Ruby solution using eval:
is_enough=->a{_,*s=a
"#{(1..s.size).find{|i|g=0;s.rotate(i-1).all?{|x|g+=eval x.tr ?:,?-;g>=0}}||:impossible}"}

Example usage:
is_enough[%w(4 3:1 2:2 1:2 0:1)] #=> "1"
is_enough[%w(4 1:1 2:2 1:2 0:1)] #=> "impossible"
is_enough[%w(4 0:1 2:2 1:2 3:1)] #=> "4"
is_enough[%w(4 1:2 2:1 4:3 0:1)] #=> "2"
is_enough[%w(4 0:1 2:2 1:2 3:1)] #=> "4"
is_enough[%w(4 0:1 0:1 4:1 0:1)] #=> "3"
is_enough[%w(8 0:1 0:1 4:1 0:1 2:1 3:1 0:0 0:1)] #=> "3"

EDIT: Corrected function name and return type.

APL (70)
{×⍴G←Z/⍨0∧.≤¨+\¨¯1⌽⌽∘K¨Z←⍳⍴K←{⎕ML←3⋄-/⍎¨⍵⊂⍨⍵≠':'}¨1↓⍵:⊃G⋄'impossible'}

Explanation:

1↓⍵: drop the first element (length), we don't need it
{...}¨: for each of the gas stations...

⎕ML←3: set ⎕ML to 3 within the inner function (changes behaviour of ⊂)
⍵⊂⍨⍵≠':': split the string on :
⍎¨: evaluate each part
-/: subtract the second number from the first (giving net effect for each gas station)

K←: store them in K
Z←⍳⍴K: get the indices for the gas station (1 to length of K), store in Z
⌽∘K¨Z: rotate K by each value of Z, giving an array of arrays
¯1⌽: rotate this array to the left by 1 (to put the unchanged one first instead of last)
+\¨: make a running sum for each inner array
0∧.≤¨: for each running sum, see if there are negative values
Z/⍨: select from Z those elements for which the running sum had no negative values
×⍴G←: store in G. If G has any elements:
:⊃G: return the first element of G.
⋄'impossible': otherwise, return impossible.

Ruby 132
g=->a{n,*a=a.map{|e|e.split(?:).map &:to_i}
(r=(0...n[0]).find{|i|a.rotate(i).inject(0){|m,(j,k)|m&&m>=0&&m+j-k}})?r+1:"impossible"}

Test:
irb(main):003:0> g[["4","1:1","2:2","1:2","0:1"]]
=> "impossible"
irb(main):004:0> g[["4","0:1","2:2","1:2","3:1"]]
=> 4

Spec requires a string to be returned in all cases.

@boothby I can't find that requirement anywhere in the spec. Can you quote?

For the example above there are 4 gas stations, and your program should return the string "1" because:

Ah screw it; Chron's solution is much shorter anyways :D

Python, 131
I find this one-liner fairly satisfying.
E=lambda s:([`i`for i in range(1,len(s)+1)if reduce(lambda r,t:r+eval(t[0]+'-'+t[-1])*(r>=0),s[i:]+s[1:i],0)>=0]+['impossible'])[0]

what is reduce() here? I am getting an error NameError: name 'reduce' is not defined

@ErHarshRathore this is Python 2. In Python 3, reduce is still in the standard lib, but it was moved to the functools module.

Yeah! I got it from functools import reduce thanks

@ErHarshRathore Additionally the backticks \i`here is equivalent tostr(i)` in Python 3.

Do you thing this post should be updated now to python 3.x?

@ErHarshRathore No. Python 2 is still a language. Python 3 is a different language. If you wish to code golf it in 3, you can post an answer in that different language.

GolfScript (72 chars)
{(~\{':'/{~}/-}%[\),1>{;.{1$-1>*+}*-1>\(+\},~"impossible"]1=}:is_enough;

Online demo
This performs the obvious brute force approach. The most interesting bit IMO is the determination of whether the partial sums of an array of delta-fuel ever drops below 0:
{1$-1>*+}*-1>

This saves 1 char over the more obvious
[{1$+}*]{0<},!

If the output were indexed at 0 rather than at 1, an alternative approach to rotating the array would be preferable:
{(;{':'/{~}/-}%:A[,,{A\{(+}*{1$-1>*+}*-1>},~"impossible"]0=}:is_enough;

But this approach isn't easily adopted to indexing at 1:
{(;{':'/{~}/-}%:A[,),1>{A\({(+}*{1$-1>*+}*-1>},~"impossible"]0=}:is_enough;

or
{(;{':'/{~}/-}%:A[,,{A\{(+}*{1$-1>*+}*-1>},{)}%~"impossible"]0=}:is_enough;


text:
shortest code to encrypt a string
Using a language of your choice write a program that takes a string as an input, and returns the string encrypted.
Algorithm:
You should assume that each character is always encoded in a byte and is ASCII-based. The extended ASCII codes are mapped to whatever is the default code page in use by the system.
You should encrypt the code in the following way:
code of first character +1, code of second character +2, code of third character +3 .....
Extended ASCII codes are based on this table:
http://www.asciitable.com/
Shortest code wins.

If you're above 128 it's not ASCII. I have no idea what you're trying to say with your example of wrapping: please rewrite it to make it clear which values come from the plaintext and which come from the key stream.

Is the requirement to jump past 0 when overflowing byte deliberate? (The successor to 255 for a byte is usually 0)

Or perhaps it's the increment that is never 0? Eg. the chipertext can be any byte value but no char will have the same chiperchar as the clearchar? Could you make the 256/0 part more clear?

Encryption algorithms that don't have keys don't seem rather useful. In fact this is just hardcoding one key for a substitution cipher.

If you're above 255, it isn't even the OEM character set. Please read http://www.joelonsoftware.com/articles/Unicode.html when you get a chance. I re-read it every few years. :)

This question has two close votes as "unclear what you're asking". I do not agree with these votes. Can you edit your question addressing the complains to ensure that no one closes it?

@Victor the problem is that I really don't get the above comments because as I see here : http://www.asciitable.com/ there are 'extended ascii characters' which are 255 . I don't know what other word should I choose. Probably 'encoding' as the above link suggests?

@user689 I edited the question. Let me know if you do agree with that or not.

@Victor, it also has 20 upvotes on a comment that says why it isn't clear, and your edit doesn't address that point.

Isn't this encoding not encryption?

@Mhmd: The "extended ASCII characters" there are not technically ASCII, hence the confusion. Add the fact that that the scheme outlined there is a non-standard one (Microsoft's "Code Page 437", which isn't even any of the standard [and typical] ISO/IEC 8859 encodings), and you can see where the confusion comes from.

GolfScript 20 19 15 12
{0)255%:0+}%

This assigns a variable to the character 0, which allows us to not define it on the first iteration of the mapping.  I love that you can do that in GolfScript!  Each iteration of the mapping increments the 0 variable, and adds it to subsequent characters of the string (which is treated like an array).
This alternate 20-character GolfScript solution using zip encounters an interesting issue:
.,,]zip{~)255%+}%''+

Try it here.  This standard online interpreter, however, treats zip differently for an array containing a string and an array.  See this vs this.  I'm not sure if an alternate version of Ruby or GolfScript is being used, or which one is considered canonical, but the second interpreter can be resolved with 2 characters:
.,,[\]zip{~)255%+}%''+

I also like a different solution for 23 characters:
1\{(@.@255%+\)@.}do]''+

The first one gives me an error message? undefined method 'rightparen' for nil:NilClass

interesting - it works with this interpreter: http://copy.sh/golfscript/?c=ImhlbGxvIHdvcmxkIgouLCxdemlwe34pMjU1JSt9JScnKw==

Hmmm. This is where I get the error; different versions of Ruby or Golfscript, maybe?

The more standard online interpreter (http://golfscript.apphb.com/) treats zip differently with an array containing a string and an array.  See http://copy.sh/golfscript/?c=WyJ6aXAiIFsxIDIgM11demlwIHAKW1sxIDIgM10gInppcCJdemlwIHA= vs http://golfscript.apphb.com/?c=WyJ6aXAiIFsxIDIgM11demlwIHAKW1sxIDIgM10gInppcCJdemlwIHA%3D

@Gareth the new 15-character solution is cooler, anyway, and works in both! :)

What's the ''+ for? Mapping a block over a string gives a string already.

@PeterTaylor Cool!  The online interpreter I was using doesn't show that, but running the code locally works as you describe.  Thanks!

BrainFuck: 21
>,[+<[->+>+<<]>.>+>,]

Assumes EOF=zero
echo -n 'My secret password is 123456!' | beef encrypt.bf
==> N{#wjiym}*{mv36HJLNPR>

Nice. And the code is encrypted too!

"Obfuscated," not "encrypted."  There is no secret key.

C — 67 56 49 characters
During compilation it might warn that q is missing a type...
q;main(p){for(;p=~getchar();)putchar(q++%255-p);}

Thanks to Josh for the significantly shorter rewrites!
$ echo 'My secret password is 123456!' | ./_encrypt
N{#wjiym}*{m����v3}�6HJLNPR>(

Confirm it handles the rollover from 255 to 1 correctly by encrypting 343 xs and checking for no xs in the output:
$ echo xxxxxxx | sed -e 's/x/xxxxxxx/g' -e 's/x/xxxxxxx/g' | ./_encrypt | grep -o x | wc -l
0

You can make this quite a bit shorter: q;main(p){for(;p>0;q*=q<255)putchar(++q+(p=getchar()));}

Wow, I'm always amazed at what people can do with normally verbose languages! Is it okay to revise my submission using it?

Go right ahead, that's why I posted it!

Would k;main(i){putchar((k=getchar())+i);k^-1&&main(i+1);} work?

@Oberon - almost, but in the xxx test it detects an x in the output.

If we can ignore integer overflow (input larger than 2^32 characters) this should work: q;main(p){for(;p>0;)putchar(++q%256+(p=getchar()));}

@Josh - almost, but seeing an x in the xxx test.

@YiminRong xs should be okay. The wrapping back to one instead of zero should just mean that there are no ASCII 0 characters in the output. Though the spec is not very clear.

@Gareth - I don't think that's what he means. If you encrypt and it gives 0, then "correct" it to 1, then accurate decryption isn't guaranteed.

@YiminRong It isn't at all clear what the OP means in this regard so either one of us may be correct here. My understanding is that each character in the string has its index (1-based) added to it. Any resulting values over 255 (outside the 1-byte range) should then wrap down to 1 (rather than 0 which would be easier).

You can test for EOF by ~p. And I think you can also make the condition p=~getchar() and then use ++q+~p (saving parentheses).

Using @ugoren's recommendations I can get it down to 49 characters, passing both test cases: q;main(p){for(;p=~getchar();)putchar(q++%255-p);}

@Josh - Wow, this is approaching specialty languages length! Thank you!

Befunge 98 - 15 bytes
:~+'U3*%1+,1+#@

Keeps a counter (starting at 0) and adds that to the ~ input. Then, computes 255 (as 85 * 3 in the form of 'U3*), then mods (%). Then, it adds 1 and prints it, then adds one to the counter, then uses # to skip over the @. At the end of the input, the IP goes the other way and hits the @, ending the program.
Alternatively, if your interpreter supports unicode, this 14 byte (13 char) solution works:
:~+'ÿ%1+,1+#@

Sample run (in command prompt, so some of the unicode characters are actually some ascii value):
This string will be encrypted using the predetermined method!2.7182818284590452353602874713526624

Output:
Ujlw%y{zrxr,äw{|1tx4zäzèÆèÅüü>öôèÉèDÖÄîHÖ£ÉÉÆóöó₧¢íÖÖVñ¥¡ó¬á^pmwrzu|v~yÇ}⌂ä|üâüâåàëäçÄÄîÉïÄæÅöòÆò

@ArlaudPierre What are you talking about? Befunge is my favorite programming language.

Is ÿ considered one or two bytes? Its value is 255 which is within one unsigned byte...

J, 21 characters
a.{~1+256|(+i.@#)a.i.

Usage (borrowing Yimin's test text):
   a.{~1+256|(+i.@#)a.i.'My secret password is 123456!'
N{#wjiym}*{m????v3}?6HJLNPR>

JavaScript, 90c
t.split("").map(function(c,a){return String.fromCharCode(c.charCodeAt(0)+a+1)}).join("")
[].map.call(t,function(c,a){return String.fromCharCode(c.charCodeAt(0)+a%255+1)}).join("")

Fiddledee

Your code doesn't wrap after 255 chars, it needs to be this: .split("").map(function(c,a){return String.fromCharCode(c.charCodeAt(0)+a%255+1)}).join("")

You can also do this and save 1 character: [].map.call(t,function(c,a){return String.fromCharCode(c.charCodeAt(0)+a%255+1)}).join("")

@A.M.K: Nice.. ducktyping the string, very clever!
Forgot the modulus -.-

@micha I will try to understand what you write later. But I can see that you can drop that 0 in .charCodeAt(0) and save one char.

You don't need the 0 in c.charCodeAt and in EcmaScript 6 (supported in Firefox & Google Chrome), you can make it even shorter: [].map.call(t,(c,a)=>String.fromCharCode(c.charCodeAt()+a%255+1)}).join("")

You can even modify the original string: [].map.call(t,(c,a)=>t[a]=String.fromCharCode(c.charCodeAt()+a%255+1)});t

Python2.7 (67 chars)
import sys;print''.join([chr((ord(x)+1)%256)for x in sys.argv[1]])

Javascript/JScript: 72 to 105 chars
Here is a Javascript/JScript attempt at making a version of this code.
I'm aware that there is another Javascript code, but that one relies on recent Javascript implementations.
That is a bad thing!!!
That code is invalid in ie8< without polyfills.
Here is my version:
function $(c){for(var i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i&255));return o;}
//function call, 105 chars, absolutely valid!

function $(c){for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i&255));return o;}
//function call, no var keyword, 101 chars, completely valid!

function $(c){for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i));return o;}
//function call, 97 chars, most likely invalid!

c='';//here goes input, output is in var `o`, dont count this line
for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i&255));
//no function call, input goes to var c, 77 chars of pure working code! valid for sure!

c='';//here goes input, output is in var `o`, dont count this line
for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i));
//no function call, input goes to var c, no char wrapping after 255, 73 chars of probably invalid code

@toothbrush gave me this answer:
i=0;while(i<c.length)c[i]=String.fromCharCode(c.charCodeAt(i++)+i%255+1)

It changes the original string and is only 72 bytes!
I don't know why he has %255+1 in the end when &255 does the same job, is faster and shorter.
But I will keep the original answer intact.

Consider this and test it with a Javascript/JScript interpreter.
I know that the 73 char version and the 97 char function call version will be invalid, but its still here!
If you will be using the code in a production environment (website), use the 105 chars long and consider changing the function name to something else (or you might have problems with jQuery and MooTools).

The 73 character version can be even shorter: i=0;while(i<c.length)c[i]=String.fromCharCode(c.charCodeAt(i++)+i).
To properly handle the wrapping of the numbers: i=0;while(i<c.length)c[i]=String.fromCharCode(c.charCodeAt(i++)+i%255+1) - this version is still shorter than the current version!
Both modify the original string.

@Ismael Miguel, No offense, but this is a code golf website; the code isn't intended to ever be used. Therefore browser compatibility isn't a consideration.

@A.M.K  Does it work? Is it short?

@IsmaelMiguel, Yes, but you said `I'm aware that there is another Javascript code, but that one relies on recent Javascript implementations.
That is a bad thing!!!`.  All I'm saying is that since this is a code golf question, that isn't a bad thing.  I've even seen answers that use features that haven't been implemented yet!

Yes, but the upvotes are based on code beauty, not functionality. Basically: they are upvoting code that MIGHT not work for an undefined time.

Python3 (99 chars)
e=''
i=0
for c in __import__("sys").argv[1]:
        i=(i+1)%255
        e+=chr(ord(c)+i)
print(e)

Example
python encrypt.py password outputs qcvw|uyl

The output for password should be qcvw|uyl.

Yeah, i fixed that, was a little bit to hectic :)

You can remove the from sys... part by doing for c in __import__("sys").argv[1].

CoffeeScript, 73 64 chars
t.replace /./g,(c,a)->String.fromCharCode c.charCodeAt()+a%255+1
[].map.call(t,(c,a)->String.fromCharCode c.charCodeAt(0)+a%255+1).join ""
Example: "Test string".replace /./g,(c,a)->String.fromCharCode c.charCodeAt()+a%255+1 outputs Ugvx%y{zrxr
Coffee to Javascript converter (paste in right box): http://js2coffee.org/
As per Ismael Miguel's comments, this method should work in IE 5.5+.

Ruby functional, 67
puts ARGV[0].bytes.map.with_index(1){|b,i|b+i%255}.map(&:chr).join

Example:
$ ruby encrypt.rb password
=> qcvw|uyl

A new user without the comment privilege suggested shortening the code to puts ARGV[0].bytes.map.with_index(1){|b,i|(b+i&255).chr}*''. I've rejected the edit as per our policy but you might want to review it and edit it in yourself and credit them.

Julia 51 (-4 if in place is allowed)
g(s)=([s.data[i]+=(i-1)%255+1 for i=1:length(s)];s)
g(s)=[s.data[i]+=(i-1)%255+1 for i=1:length(s)] # in place version
julia> g("a"^256) # ^ operator repeats strings
"bcdefghijklmnopqrstuvwxyz{|}~\x7f��������������������������������������������������������������������������������������������������������������������������������\0\x01\x02\x03\x04\x05\x06\a\b\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\e\x1c\x1d\x1e\x1f !\"#\$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`b"

Note that 0 is not allowed as an encryptor, so in your example you shouldn't see a outputted.

Or maybe it is, once I reread the specs, it might be asking for a non-reversible encryption.

No I think you are right. I updated it, which adds a few letters.

Haskell, 77C 59C
import Data.Char
e s=h s 1
h""_=""
h(x:s)i=(chr(mod((ord x)+i)128)):h s(i+1)

v2
import Data.Char
e s = map chr(zipWith(+)(map ord s)[1..])

I am assuming that input doesn't need to be on STDIN.
Example run:
*Main> e "hello"
"igopt"

GolfScript, 27 characters
[.,,\]zip[{{+}*255%1+}/]''+

Hmmm...seems a bit long. Maybe I should stick to J.

Ruby, 45 39 bytes
gets.chars{|c|putc(c.ord+$.)%256;$.+=1}

Erlang: 60C
Not the smallest or prettiest, but this one can be run standalone in the command line.
Set T to your text.
{S,_}=lists:mapfoldl(fun(C,I)->{C+I,(I+1)rem 255}end,1,T),S.

Yields:
    "qcvw|uyl"

Rebol, 58 chars
s: input forall s[s/1: mod(index? s)+(to-integer s/1)256]s

Groovy, 53 Characters
i=0;args[0].chars.collect{(char)it+(++i%255)}.join()

Dart, 68
f(s,{i=1})=>new String.fromCharCodes(s.runes.map((c)=>(c+i++)%255));

Example:
f('My secret password is 123456!');
> N{#wjiym}*{mv3}6HJLNPR>

Perl, 54 char
$i=1;print map{chr((ord()+$i++)%256)}split//,$ARGV[0];

Example:
perl encrypt.pl password
> qcvw|uyl


text:
The answer to life, the universe, and everything
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.

You should probably ban sleep and time functions, or else the solution will just be sleep(75);print 41+1

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

@tecywiz121 you beat me to it!

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

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

@Fozzedout the entire script must run in 75 seconds

@Josh Not true; for example, Java has System.currentTimeMillis()

@Josh Agreed, this should be popularity contest. As it stands there's nothing particularly interesting about this that makes it a code golf. Not to mention that the rules aren't even particularly well defined. The only real way to guarantee time is to use some form of timer. I might be inclined to close vote

Sorry I'm new here, if needed I can change it to a popularity contest. edit changed.

http://www.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.

I accidentally made mine take 10 minutes! :O

I have found ways to generate 42 in a funny way, but they took much much more than 75s. Making a algorithm that take approx. 75 sec is really hard.

if it takes 7.5 milion years I think it could be accepted as answer :P

Well, darn.  The time thing makes the most interesting solution too simple:  If we define a=0, b=1,...z=25, then you can sum "earth" (and subtract length("earth") due to it not finishing the calculation) to get 42...

The answer to Life, the Universe, and everything = 2**5+0x15f%11

Proud to be the 42nd upvote on this question :)

The votes on this are so almost perfect... is tempted to downvote to get the vote count back to 42

@Doorknob I downvoted becuase 1) it's an off-topic question and 2) I'm getting the vote count back to 42.

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

So you'll either find a new number that satisfies this equation or you'll print 42 :)

It didn't print anything on my pc

@FezVrasta, because the last line went missing. doh!

Wow! Perfect math rebus and the overclocking thing... ha ha ha +1!

I just had to upvote this answer from 41 to 42..

I upvoted your question to 42. I hope it stays at that number ^^

it's funny that this answer has a hard cap score of 42 (not upvoting)

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

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.

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 :(

@FezVrasta Sorry, I accidentally added some wrong code. Fixed it now, should work.

awesome, it works :) now we need a bigger computer to compute the question!

"I may be a sorry case, but I don't write jokes in base-13." - DNA

No, the question, as generated by scrabble tiles on the original radio series, was What do you get when you multiply six by nine?

It is the ultimate question after all; best not to misquote! :)

Actually Deep Thought didn't know the ultimate question, and by the way the Ultimate question was not that one, that was just a guess stated by Arthur :P But I guess this is not the right place to talk about this

@TRiG fixed now!

This is now sitting at 42 votes. Do I want more votes, or do I want the coolest possible score for this question?

@LegoStormtroopr no, this answer needs to be locked in as it stands right now. No more rep for you.

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

Looks like your Deep Thought has a different idea, it returns me 40 :P

I've used Notepad++, I've a Windows 8 x64

No luck even with NotePad, the version with the exclamation mark instead works

Cool, can you guess how it works?

Ehm no clues sorry

Why would your first example ever produce 42? The code is only 40 bytes, including the newline. Unless you had some extra characters in there (maybe a newline at the end) it should always produce 40.

Also, with your second example, you could change it to @<space><space>echo %~z0, so that the output is "42", and not "42!".

@YiminRong, The carriage return character for NotePad is always two bytes.

@unclemeat - are you terminating the last line with a carriage return?

Of course not, if I did that I would get the answer 42, but that isn't included in your answer.

Notepad++ and wordpad won't effect the answer I've submitted as an edit.

Notepad++ and Wordpad weren't the problem - their newline characters are both 2 bytes as well.

@YiminRong, the spaces are quite obvious. Anyone who will test out your answer will copy / paste the code exactly as it appears.

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 - thank you, much appreciated!

ping is well known as a sleep equivalent in batch files. http://stackoverflow.com/questions/166044/sleeping-in-a-batch-file for instance.

@BrianMinton - I would consider it relying on a side effect. ping is not meant to be a sleep function. Otherwise, resource kits wouldn't see the need to provide an actual sleep function.

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"

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.

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

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

while-looping until clock() exceeds some value seems to violate the no sleep() rule, since that's basically a cpu-intensive sleep

popularity-contest.

@ArlaudPierre It was [tag:code-golf] when I submitted the answer. Anyways, it's fixed now.

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

How do you ensure it lasts 75 seconds?

@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.

Update: ... well now it prints Took 25 seconds; seed was 3771996 on my average-performance laptop. So, uhh... I lied. :P

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

C# - 151 Characters
class P
{
   static void Main()
   {
      var w = new System.Diagnostics.Stopwatch();
      w.Start();
      while (w.ElapsedMilliseconds < 75000);
      System.Console.Write((int)'*');
   }
}

How is this not equivalent to thread sleep?

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.

I know functionally 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.

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.

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

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

Much much more than 75 seconds...

but it's tottaly worth!

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

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.

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.

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

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

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

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.

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

you are using "sleep"

oops, read it as can use sleep -10 for me!

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.

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

I'm getting a syntax error... Unexpected token >

I have this working on Firefox 26.0 which accepts the x=x=>f(x) notation... What version are you running this on?

i'm running chrome 31 on windows 7 ...

@rafaelcastrocouto Ah, sadly fat arrow notation used to define the two functions in each of the statements only works for Firefox 22 and above...

i'm almost crying ... your solution is indeed beautyful!

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


text:
Battleship game
Given the scheme of the fleet of the human player, let the user choose which coordinates attack each turn.
The "computer player" will then attack on its turn following the classic rules of battleship. (The computer player must be able to win, you can't make the computer attack every turn the same cell)
The schemes must contain all the needed ships, this is the list:
[ ][ ]               x 4

[ ][ ][ ]            x 3

[ ][ ][ ][ ]         x 2

[ ][ ][ ][ ][ ][ ]   x 1

The scheme must follow the example below, and must be one for each player.
[ ][ ]   [ ]      [ ][ ][ ][ ]
         [ ]
[ ]      [ ]   [ ][ ][ ]   [ ]
[ ]                        [ ]
[ ]
[ ]            [ ]         [ ]
               [ ]         [ ]
[ ][ ]                     [ ]

            [ ][ ][ ][ ][ ][ ]

To input the player scheme you can just hard-code it in your script or let the user insert it in some way (use a specific char to separate rows or let user inser one row per time etc, up to you), the important thing is that your player must be able to easily insert a new scheme (no minified/compressed input so).
The fleet owned by the computer must be randomly generated by the script.
The coordinates are a number(1-10) and a letter(A-L), this is an example battlefield with coordinates:
      A  B  C  D  E  F  G  H  I  L
   |‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
 1 | [ ][ ]   [ ]      [ ][ ][ ][ ]
 2 |          [ ]
 3 | [ ]      [ ]   [ ][ ][ ]   [ ]
 4 | [ ]                        [ ]
 5 | [ ]
 6 | [ ]            [ ]         [ ]
 7 |                [ ]         [ ]
 8 | [ ][ ]                     [ ]
 9 |
10 |             [ ][ ][ ][ ][ ][ ]

Each turn the script must ask which coordinates hit, and return an indication:

not hit = the selected coordinates doesn't match a part of a ship
hit = the selected coordinates does match part of a ship but the ship is not yet sunk
hit and sunk =  the selected coordinates does match part of a ship and the ship is sunk

Then it will have to make the computer hit a cell (bonus points if you can write a smart script that will be challenging) and indicate to user which cell was hit and if one of his ships was hit (same indications of above).
Example "gameplay" log:
Your coordinates: A1
hit
Enemy coordinates: C1
not hit
Your coordinates: B1
hit and sunk

if the user chooses two times the same coordinates consider it as not hit or just ignore it
The expected final outputs (when one of the two players has not ships available) are the two schemes with the coordinates hit by the computer player marked with an x, example of the first scheme:
[x][x]   [x]      [x][x][x][ ]
 x       [x]
[ ] x    [x]   [ ][ ][x]   [x]
[ ]                        [x]
[ ]       x
[x]            [x]         [ ]
               [x]    x    [ ]
[ ][ ] x                   [ ]

    x       [ ][ ][x][ ][ ][ ]

It's probably not the easiest code-golf challenge here but as usual, the shortest code will win.

Two Face: B12!
The Riddler: Hit! And my favorite vitamin might I add.
~ Batman Forever

You sunk my battleship.

Hmm, you did not specify that the algorithm must be intelligent, and since this is code-golf, people will exploit this to make code shorter, making the computer play [A1][A2][A3][A4][A5]... Further, they will hardcode computer ships in stupid positions to make code even shorter. And more, the rules does not stop people to make a cheating computer intelligence that directly looks the user's ship positions.

@Victor The ship positions for the computer must be randomly generated (look at the question again)

@victor actually generate random coordinates for where the computer should attack takes less code then use your method in most of the languages, also I've specified that would be nice have a challenging enemy, but it's up to you this, I think it's already an enough long golf script

Well, better late than never. I remembered doing something like this in a school class long time ago... Ungolfed and waaaaaay too long.
#include <iostream>
#include <ctime>
#include <sstream>
#include <cstdlib>
using namespace std;

class board{
private:
    char grid[10][10];
public:
    void initializeGrid(){
        for (int row=0; row<10; row++){
            for (int column=0; column<10; column++){
                grid[row][column]='~';
            }
        }
    }
    void displayGrid(bool hideShips=false){
        int y=10;
        for (int i=0; i<10; i++){
            if (y!=10){cout<< " ";}
            cout<<y;
            for (int c=0; c<10; c++){
                cout<<" ";
                if (grid[i][c]=='X'){
                    if (hideShips==true){
                        cout<<"~";
                    }else{
                        cout<<grid[i][c];
                    }
                }else{cout<<grid[i][c];}
            }
            y--;
            cout<<endl;
        }
        cout<<"   A B C D E F G H I J"<<endl;
    }
    char getSpace(int x, int y){
        return grid[y][x];
    }
    void addSpace(char space, int x, int y){
        grid[y][x]=space;
    }
};

class ship{
private:
    int length;
    board* boardOP;
public:
    ship(int L, board* BOP){
        length=L;
        boardOP=BOP;
    }
    bool buildShip(int *X, int *Y, int dX, int dY, board *boardOP){
        int shipStore[10]={-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
        for(int i=0; i<length; i++){
            shipStore[i*2]=*X;
            shipStore[i*2+1]=*Y;
            if (*Y+dY<10&&*Y+dY>-1
              &&*X+dX<10&&*X+dX>-1
              &&boardOP->getSpace(*X+dX,*Y+dY)=='~'){
                *Y=*Y+dY;
                *X=*X+dX;
            }else{return false;}
        }
        for(int c=0; c/2<length; c+=2){
            boardOP->addSpace('X',shipStore[c],shipStore[c+1]);
        }
        return true;
    }
    int getLength(){return length;}
};

class player{
protected:
    board* thisBoardOP;
    board* otherBoardOP;
    int X;
    int Y;
    int hits;
public:
    virtual void go(){}
    player(){
        hits=0;
    }
    bool won(){
        if(hits==17){return true;
        }else{return false;}
    }
    bool hit(){
        if (otherBoardOP->getSpace(X-1,10-Y)=='X'){
            cout<<"hit!"<<endl;
            hits++;
            otherBoardOP->addSpace('#',X-1,10-Y);
            return true;
        }else{
            cout<<"miss!"<<endl;
            otherBoardOP->addSpace('O',X-1,10-Y);
            return false;
        }
    }
    void arrangeShips(){
        ship aircraftCarrier(5,thisBoardOP);
        positionShip(&aircraftCarrier);

        ship battleship(4,thisBoardOP);
        positionShip(&battleship);

        ship cruiser(3,thisBoardOP);
        positionShip(&cruiser);

        ship destroyer(3,thisBoardOP);
        positionShip(&destroyer);

        ship patrolBoat(2,thisBoardOP);
        positionShip(&patrolBoat);
    }
    void positionShip(ship* type){
        while(1){
            int dY=0;
            int dX=0;
            dX=(rand()%2)-(rand()%2);
            if(dX==0){
                dY=(rand()%2);
                if(dY==0){(dY)--;}
            }else{dY=0;}
            int Y=(rand()%10);
            int X=(rand()%10);
            if (thisBoardOP->getSpace(X,Y)=='~'){
                if (type->buildShip(&X,&Y,dX, dY,thisBoardOP)==false){
                    dX*=-1;
                    dY*=-1;
                    if (type->buildShip(&X,&Y,dX,dY,thisBoardOP)==true){return;}
                }else{return;}
            }
        }
    }
};

class human: public player{
public:
    human(board* tBOP, board* oBOP){
        thisBoardOP=tBOP;
        otherBoardOP=oBOP;
    }
    void go(){
        setXY();
        hit();
        cout<<X<<endl;
        cout<<Y<<endl;
    }
    void setXY(){
        string input;
        while(1){
            do{
                cout<<endl<<"Enter x coordinate:"<<endl;
                char letterX='\0';
                cin>>input;
                if (input.length()==1){letterX=input[0];}
                X=convertLetter(letterX);
                if(X==0){cout<<endl<<"Please enter a valid letter between A-J"<<endl;}
            }while(X==0);
            do{
                cout<< endl<<"Enter y coordinate:"<<endl;
                cin>>input;
                stringstream(input)>>Y;
                if(Y>10||Y<1){cout<<"Please enter a valid number between 1-10"<<endl;}
            }while(Y>10||Y<1);
            if(otherBoardOP->getSpace(X-1,10-Y)=='#'
             ||otherBoardOP->getSpace(X-1,10-Y)=='O'){
                cout<<endl<<"You cannot shoot a space that has already been hit!"<<endl;
            }else{break;}
        }
    }
    int convertLetter(char letter){
        if (int(letter)>64&&int(letter)<75){
            return int(letter)-64;
        }else if(int(letter)>96&&int(letter)<107){
            return int(letter)-96;
        }
        return 0;
    }
};

class computer: public player{
private:
    int originX;
    int originY;
    int vX;
    int vY;
    bool foundEnd1;
    bool foundEnd2;
    bool foundDirection;
    bool oppositeCheck;
    int distance;
    int count;
public:
    computer(board* tBOP, board* oBOP){
        thisBoardOP=tBOP;
        otherBoardOP=oBOP;
        originX=0;
        originY=0;
        vX=0;
        vY=0;
        foundEnd1=false;
        foundEnd2=false;
        foundDirection=false;
        oppositeCheck=false;
        distance=2;
        count=0;
    }
    void go(){
        setXY();
        if(hit()==true){
            if(originX==0){
                originX=X;
                originY=Y;
            }else if(foundDirection==false){
                foundDirection=true;
                if(oppositeCheck==true){
                    if(vX<0||vY<0){foundEnd1=true;
                    }else{foundEnd2=true;}
                }
            }
        }else if(foundDirection==true){
            if (X-originX>0||Y-originY>0){foundEnd1=true;
            }else{foundEnd2=true;}
        }
    }
    void setXY(){
        if(originX!=0){
            if(foundEnd1==false
             ||foundEnd2==false){
                if(foundDirection==false){
                    findDirection();
                }else{
                    findRest();
                }
            }
            if(foundEnd1==true
             &&foundEnd2==true){
                originX=0;
                originY=0;
                vX=0;
                vY=0;
                foundEnd1=false;
                foundEnd2=false;
                foundDirection=false;
                oppositeCheck=false;
                distance=2;
                count=0;
            }
        }
        if (originX==0){
            do{
                X=(rand()%10)+1;
                Y=(rand()%10)+1;
            }while(otherBoardOP->getSpace(X-1,10-Y)=='O'
                 ||otherBoardOP->getSpace(X-1,10-Y)=='#');
        }
    }
    void findDirection(){
        if(count==0){
            vX=(rand()%2)-(rand()%2);
            if(vX==0){
                vY=(rand()%2);
                if(vY==0){(vY)--;}
            }else{vY=0;}
        }
        while(count<4){
            if(count==2){oppositeCheck=false; int i=vX; vX=vY; vY=i;
            }else if(count!=0){oppositeCheck=true; vX*=-1; vY*=-1;}
            count++;
            if(originX+vX<11&&originX+vX>0
             &&originY+vY<11&&originY+vY>0
             &&otherBoardOP->getSpace((originX+vX)-1,10-(originY+vY))!='#'
             &&otherBoardOP->getSpace((originX+vX)-1,10-(originY+vY))!='O'){
                X=originX+vX;
                Y=originY+vY;
                return;
            }
        }
        foundEnd1=true;
        foundEnd2=true;
    }
    void findRest(){
        int adjustment=0;
        if(foundEnd1==true){
            if(vX<0||vY<0){adjustment=1;
            }else{adjustment=-distance;}
        }else if(foundEnd2==true){
            if(vX<0||vY<0){adjustment=-distance;
            }else{adjustment=1;}
        }else{
            adjustment=(rand()%2);
            if(adjustment==0){adjustment=-distance;}
        }
        if (vX<0||vY<0){adjustment*=-1;}
        int i=0;
        while(i<2&&(foundEnd1==false||foundEnd2==false)){
            if (vX==0){
                if(originY+vY+adjustment>0
                 &&originY+vY+adjustment<11
                 &&otherBoardOP->getSpace(originX-1,10-(originY+vY+adjustment))!='#'
                 &&otherBoardOP->getSpace(originX-1,10-(originY+vY+adjustment))!='O'){
                        Y=originY+vY+adjustment;
                    if(adjustment==1||adjustment==-1){vY+=adjustment;}
                    distance++;
                        return;
                }
            }else{
                if(originX+vX+adjustment>0
                 &&originX+vX+adjustment<11
                 &&otherBoardOP->getSpace((originX+vX+adjustment)-1,10-originY)!='#'
                 &&otherBoardOP->getSpace((originX+vX+adjustment)-1,10-originY)!='O'){
                        X=originX+vX+adjustment;
                    if(adjustment==1||adjustment==-1){vX+=adjustment;}
                    distance++;
                        return;
                }
            }
            if(adjustment==1){adjustment=-distance; foundEnd1=true;
            }else if(adjustment==-1){adjustment=distance; foundEnd2=true;
            }else if(adjustment==distance){adjustment=-1; foundEnd1=true;
            }else{adjustment=1; foundEnd2=true;}
            i++;
        }

    }
};

int main(){
    srand((unsigned int)(time(0)));

    board boardO1;
    boardO1.initializeGrid();

    board boardO2;
    boardO2.initializeGrid();

    human humanO(&boardO2,&boardO1);
    humanO.arrangeShips();

    computer computerO(&boardO1,&boardO2);
    computerO.arrangeShips();

    player* playerOP=&humanO;

    while(1){
        boardO1.displayGrid(true);
        cout<<endl;
        boardO2.displayGrid();
        playerOP->go();
        if(playerOP->won()==true){
            cout<<endl;
            if(playerOP==&humanO){
                cout<<"You win!"<<endl;
            }else{
                cout<<"Computer wins!"<<endl;
            }
            cout<<endl;
            boardO1.displayGrid(true);
            cout<<endl;
            boardO2.displayGrid();
            break;
        }
        if (playerOP==&humanO){playerOP=&computerO;
        }else{playerOP=&humanO;}
    }

    return 0;
}

Result:
./a.out
10 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 9 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 8 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 7 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 6 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 5 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 4 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 3 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 2 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 1 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
   A B C D E F G H I J

10 ~ ~ ~ ~ ~ ~ ~ ~ X ~
 9 ~ ~ ~ X ~ ~ ~ ~ X ~
 8 X ~ ~ X ~ ~ ~ ~ X ~
 7 X ~ ~ X ~ ~ ~ ~ X ~
 6 X ~ ~ ~ ~ X X X X ~
 5 X ~ ~ ~ ~ ~ ~ ~ ~ ~
 4 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 3 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 2 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 1 ~ ~ ~ ~ ~ ~ ~ ~ X X
   A B C D E F G H I J

Enter x coordinate:
d

Enter y coordinate:
4
hit!
4
4
10 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 9 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 8 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 7 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 6 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 5 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 4 ~ ~ ~ # ~ ~ ~ ~ ~ ~
 3 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 2 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 1 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
   A B C D E F G H I J

10 ~ ~ ~ ~ ~ ~ ~ ~ X ~
 9 ~ ~ ~ X ~ ~ ~ ~ X ~
 8 X ~ ~ X ~ ~ ~ ~ X ~
 7 X ~ ~ X ~ ~ ~ ~ X ~
 6 X ~ ~ ~ ~ X X X X ~
 5 X ~ ~ ~ ~ ~ ~ ~ ~ ~
 4 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 3 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 2 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 1 ~ ~ ~ ~ ~ ~ ~ ~ X X
   A B C D E F G H I J
miss!
10 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 9 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 8 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 7 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 6 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 5 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 4 ~ ~ ~ # ~ ~ ~ ~ ~ ~
 3 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 2 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 1 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
   A B C D E F G H I J

10 ~ ~ ~ ~ ~ ~ ~ ~ X ~
 9 ~ ~ ~ X ~ ~ ~ ~ X ~
 8 X ~ ~ X ~ ~ ~ ~ X ~
 7 X ~ ~ X ~ ~ ~ ~ X ~
 6 X ~ ~ ~ ~ X X X X ~
 5 X ~ ~ ~ ~ ~ ~ ~ ~ ~
 4 ~ ~ ~ O ~ ~ ~ ~ ~ ~
 3 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 2 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 1 ~ ~ ~ ~ ~ ~ ~ ~ X X
   A B C D E F G H I J

Enter x coordinate:
d

Enter y coordinate:
7
miss!
4
7
10 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 9 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 8 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 7 ~ ~ ~ O ~ ~ ~ ~ ~ ~
 6 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 5 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 4 ~ ~ ~ # ~ ~ ~ ~ ~ ~
 3 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 2 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 1 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
   A B C D E F G H I J

10 ~ ~ ~ ~ ~ ~ ~ ~ X ~
 9 ~ ~ ~ X ~ ~ ~ ~ X ~
 8 X ~ ~ X ~ ~ ~ ~ X ~
 7 X ~ ~ X ~ ~ ~ ~ X ~
 6 X ~ ~ ~ ~ X X X X ~
 5 X ~ ~ ~ ~ ~ ~ ~ ~ ~
 4 ~ ~ ~ O ~ ~ ~ ~ ~ ~
 3 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 2 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 1 ~ ~ ~ ~ ~ ~ ~ ~ X X
   A B C D E F G H I J
miss!
10 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 9 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 8 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 7 ~ ~ ~ O ~ ~ ~ ~ ~ ~
 6 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 5 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 4 ~ ~ ~ # ~ ~ ~ ~ ~ ~
 3 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 2 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 1 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
   A B C D E F G H I J

10 ~ ~ ~ ~ ~ ~ ~ ~ X ~
 9 ~ ~ ~ X ~ ~ ~ ~ X ~
 8 X ~ ~ X ~ ~ ~ ~ X ~
 7 X ~ ~ X ~ ~ ~ ~ X ~
 6 X ~ ~ ~ ~ X X X X ~
 5 X ~ ~ ~ ~ ~ ~ ~ ~ ~
 4 O ~ ~ O ~ ~ ~ ~ ~ ~
 3 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 2 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
 1 ~ ~ ~ ~ ~ ~ ~ ~ X X
   A B C D E F G H I J

Enter x coordinate:
d

Enter y coordinate:
4

You cannot shoot a space that has already been hit!

Since this is a rather involved problem, I'll be going at it step by step and posting here.
First part, computer board generation:
I used a very simple (yet rules-abiding) algorithm to determine where to put the boats.
from random import randint as t
r=range
a=10
d=(0,9)
s=[0]*a
c = [['' for _ in r(a)] for _ in r(a)]
for _ in "1234":
 k=t(0,6)
 c[k][s[k]],c[k][s[k]+1]=['d'+_]*2
 s[k]+=2
for _ in "123":
 k=t(0,6)
 while(s[k]>7):
  k=t(*d)
 c[k][s[k]],c[k][s[k]+1],c[k][s[k]+2]=['s'+_]*3
 s[k]+=3
for _ in "12":
 k=t(0,8)
 while(s[k]>6):
  k=t(*d)
 for q in r(4):
  c[k][s[k]+q]='r'+str(_)
 s[k]+=4
 for _ in r(0,6):
  c[9][s[9]+_]='b1'
s[9]+=6

#Testing
for line in c:
 print(line)

A pretty standard output for the algorithm is:
['', '', '', '', '', '', '', '', '', '']
['d1', 'd1', 's1', 's1', 's1', 'r1', 'r1', 'r1', 'r1', '']
['d2', 'd2', 'd3', 'd3', '', '', '', '', '', '']
['s3', 's3', 's3', 'r2', 'r2', 'r2', 'r2', '', '', '']
['s2', 's2', 's2', '', '', '', '', '', '', '']
['d4', 'd4', '', '', '', '', '', '', '', '']
['', '', '', '', '', '', '', '', '', '']
['', '', '', '', '', '', '', '', '', '']
['', '', '', '', '', '', '', '', '', '']
['b1', 'b1', 'b1', 'b1', 'b1', 'b1', '', '', '', '']


text:
I'm walking around manhattan, how far am I from my hotel?
The unnecessary and convoluted story
I am walking around manhattan, block by block and my feet have gotten tired and want to go back home.
The traffic is pretty bad, but fortunately I'm very rich and I have a helicopter on standby at the hotel. But I need them to know how much fuel to pack for the flight and for that they need to know my direct distance from the hotel. I did remember which blocks I walked and can tell them what route I took. This distance needs to be precise though, if they are too short we won't make it back, too long and I've bought fuel I can't use.
Can you write me a program to convert that into the distance they will have to travel on their flight to fetch me?
Specification:
Write me a function that:

Accepts a list or string of blocks walked relative to an arbitrary grid:

U p, D own, L eft and R ight.
Can be either upper or lower case - eg. if its shorter to use u instead of U go ahead.
An invalid direction has undefined behaviour - eg. a direction of X can cause a failure.

Returns a float/decimal/double that is twice the straight line distance from the point of origin.

For illustration and clarification:

My trip could have just as easily been recorded as "luluu..." or ['l','u','l'...] but it must be recorded as Up, Down, Left, Right.

You are enough rich to have an helicopter but you care if some extra fuel is bought? :O

@fezvrasta because I'm stingy.

Way to mess with my head by not making this about Manhattan distance.

The correct answer is "It doesn't matter. You're a rich guy, so you reach into your pocket, pull out a wad of $20's, and wave it in the air to attract the attention of a cabby; you are then set upon by a group of kindergarten thugs who rob you and beat you to a bloody pulp. You are then arrested for littering and public vagrancy, charged with terrorism for attempting to cause mass panic and a pandemic by spreading your bodily ooze across a public sidewalk, convicted, sent to prison, and locked up with a cellmate nicknamed Brutus who takes a real strong liking to you. Welcome to New York!"

Kendall says this isn't  about manhattan distance? "up" and "down" are not clear. Is this to mean that you made left hand turns, and this is as if you were on a map of manhattan, or are you just actually talking about manhattan distance?

@McKay I interpret it as directions on a map, anyway (otherwise it'd probably be "forward" and "back"), and the distance measure is rather unambiguous "twice the straight line distance from the point of origin", so no manhattan distance).

@FireFly but he's traveling in manhattan distance? And he's not making turns. the question doesn't say how we're supposed to interpret the directions. He could be making left and right turns? and "Up" and "Down" could be on a map, but in Manhattan, "up" and down don't correspond to street directions, because the grid is off by what 30 degrees from north? Also, in Manhattan the blocks are not even. Sure he references taxicab geometry, which alleviates those two concerns, but still doesn't fix left and right as well as up and down.

Try using North, South, etc.

@McKay I've added an illustration to clarify this.

@FireFly My thought was that I am travelling via manhattan distance, by my helicopter isn't.

@LegoStormtroopr aha. Call me stupid, but... how do you get ~3.64 for the flight distance? :D  By my calculations the total travel distance should be 2 × (3 × √2) ≈ 8.49 (twice the distance between the coordinates).

@FireFly Cause I'm a moron who is bad at math and doesn't double check things :/

Good thing you're walking. One-way streets make it a lot more interesting. And good thing it's a "modern" grid city; even natives have been known to get lost in Boston.

Am i missing something ? because assuming the co-ordinates as (3,4) and (6,7) the distance is square root of square(6-3) + square(7-4) ~= 4.24

@Shiva the helicopter has to fly out to get me and then take me back to the hotel.

I don't like your map. The little flashy grey dots hurt my head. :P

@JamesWebster You jerk. I didn't see them until you pointed them out.

J, 17 characters
2*|+/0j1^'urdl'i.

Uses the fact, that the powers of j represent the proper directions.

'urdl'i. take string and calculate indices (0 for 'u', 1 for 'r', ...)
0j1^ transforms into the direction in the complex plane using the corresponding power of j.
+/ sums up the single steps
2*| two times the modulus

Example:
> 2*|+/0j1^'urdl'i.'uuuudrrrl'
7.2111

Nice job. Maths knowledge for the win. :-)

Make this "non-extended" ASCII and then it's just 15 bytes (because you don't use the eighth bit).

Python 2.7 56 58 56 51 48
With the stolen Number One Dime from Scrooge McDuck, I made my fortune and now have more wealth than Scrooge.
y=lambda s:2*abs(sum(1j**(ord(i)%15)for i in s))

Python 2.7 - 61 53 50 (case insensitive)
y=lambda s:2*abs(sum(1j**(ord(i)%16%9)for i in s))

Implementation
>>> from random import sample
>>> y=lambda s:2*abs(sum((-1j)**(ord(i)%15)for i in s))
>>> path=sample('RLUD'*1000, 100)
>>> y(path)
20.0
>>> path=sample('RLUD'*1000, 100)
>>> y(path)
34.058772731852805

I am getting IndexError: list index out of range. What form should the input have?

@plannapus: I have added an implementation section

Ah and it was %5 not %8. Ok it makes more sense now :)

-1 (plus updated lambda conventions)

APL (29)
{|+/2 0j2×-⌿2 2⍴+/'URDL'∘.=⍵}

e.g.
     {|+/2 0j2×-⌿2 2⍴+/'URDL'∘.=⍵} 'UUUUDRRRL'
7.211102551

Explanation:

+/'URDL'∘.=⍵: see how often the characters URDL occur in the argument
-⌿2 2⍴: subtract the U value from the D value, and the R value from the L value
2 0j2×: multiply the vertical value by 2 and the horizontal value by 2i
+/: sum
|: magnitude

Ruby 1.9+ (67)
f=->s{2*(((g=s.method :count)[?U]-g[?D])**2+(g[?R]-g[?L])**2)**0.5}

Example
f["DRUULULLULL"] => 10.0
f["UUUUDRRRL"] => 7.211102550927978

perl6: 44 chars
2*abs [+] i <<**>>%(<U R D L>Z ^4){get.comb}

get.comb gets one line of input and splits into characters
<U R L D> is a list of words, chars in this case
(1,2,3) Z (4,5,6) == (1,2), (2,5), (3,6), so it zips 2 lists into each other, making a list of parcels that %() turns into a hash
<<**>> does pairwise **, extending the shorter list to fit the longer. Shorter list happens to only be i
[+] sums all elements of a list, abs takes the modulus for complex numbers

Yes, I removed all possible spaces.

Mathematica 92 49
Calle deserves full credit for streamlining the code.
f@l_:=2 N@Norm[Tr[l/.{"r"→1,"l"→-1,"u"→I,"d"→-I}]]

Example
f[{"u", "u", "u", "u", "d", "r", "r", "r", "l"}]

7.2111

You're doing a lot of work that isn't required by the OP, f@l_ := 2 N@Norm[Tr[l /. {"r" -> 1, "l" -> -1, "u" -> I, "d" -> -I}]] will suffice.

I get 2 Norm[(2. + 2. I) + "U" + "X"] as the output for your code.

Yes, but the OP says it's OK to fail with such input. That is how I and everyone else interpret it. I can't read these other languages, but you will see that they often hardcode for u, r, l and d.

Ok. Got it. Thanks for pointing that out.

If you replace two remaining pairs of parentheses with @s you get another two characters less.

shrx, I don't understand. The code has no parentheses.

PHP, 67
function f($a){foreach($a as$d)@$$d++;return 2*hypot($U-$D,$L-$R);}

Example:
<?php
var_dump(f(array('U', 'U', 'U', 'U', 'D', 'R', 'R', 'R', 'L')));

>float(7.211102550928)

Julia, 45
f(l)=2*abs(sum([im^(c=='d'?3:c) for c in l]))

Stole the i to powers trick. Also all the characters except d have values that work as acceptable powers for i.

Python 2.7 - 65
Nice and short one, this uses complex numbers to step through the plane:
x=lambda s:2*abs(sum([[1,-1,1j,-1j]['RLUD'.index(i)]for i in s]))

Props to DSM and Abhijit in other questions that showed me the use of 1j to calculate this.

Can 1j be written as j, -1j as -j? Also, does this handle upper and lower input, or only upper?

Uncle Scrooze, I hate you. You should at least leave some money for your nephews.

@DavidCarraher: No you can't. It would be impossible to differentiate between the variable j and the imaginary unit j

Didn't you say it was supposed to output twice the distance? when trying with UUUUDRRRL i'm getting 3.606 with this function instead of 7.21.

@plannapus Yeah I have a bad habit of adding code then changing it without updating my answer :(

You can save 2 more characters, by multiplying the constants by 2 instead of multiplying the final result.

R, 86 74 56 characters
Ok it's actually way shorter with imaginary numbers indeed:
2*Mod(sum(sapply(scan(,""),switch,u=1i,d=-1i,l=-1,r=1)))

Usage:
> 2*Mod(sum(sapply(scan(,""),switch,u=1i,d=-1i,l=-1,r=1)))
1: u u u u d r r r l
10:
Read 9 items
[1] 7.211103

Old solution at 74 characters with xy coords:
2*sqrt(sum(rowSums(sapply(scan(,""),switch,u=0:1,d=0:-1,l=-1:0,r=1:0))^2))

Usage:
> 2*sqrt(sum(rowSums(sapply(scan(,""),switch,u=0:1,d=0:-1,l=-1:0,r=1:0))^2))
1: u u u u d r r r l
10:
Read 9 items
[1] 7.211103

Takes input as stdin, need to be lower-case and space-separated. Use x-y coordinates starting from (0,0).

k (50 49)
{2*sqrt x$x:0 0f+/("udlr"!(1 0;-1 0;0 -1;0 1))@x}

Example
{2*sqrt x$x:0 0f+/("udlr"!(1 0;-1 0;0 -1;0 1))@x}"uuuudrrrl"
7.211103

Java, 185, 203, 204, 217, 226
class A{public static void main(String[] a){int x=0,y=0;for(int i=0;i<a[0].length();i++) switch(a[0].charAt(i)){case'U':y++;break;case'D':y--;break;case'L':x++;break;case'R':x--;}System.out.print(Math.hypot(x,y)*2);}}

I did assume that each "U" was "1 up", so two units up would be "UU"
Edit: swapped out switch for ifs
class A{public static void main(String[]a){int x=0,y=0;for(int i=0;i<a[0].length();i++){int c=a[0].charAt(i);if(c=='U')y++;if(c=='D')y--;if(c=='L')x++;if(c=='R')x--;}System.out.print(Math.hypot(x,y)*2);}}

Moved for iterator
class A{public static void main(String[]a){int x=0,y=0;for(int i=0;i<a[0].length();){int c=a[0].charAt(i++);if(c=='U')y++;if(c=='D')y--;if(c=='L')x++;if(c=='R')x--;}System.out.print(Math.hypot(x,y)*2);}}

No longer takes input as string, rather array of directions
class A{public static void main(String[]a){int x=0,y=0;for(String s:a){char c=s.charAt(0);if(c=='U')y++;if(c=='D')y--;if(c=='L')x++;if(c=='R')x--;}System.out.print(Math.hypot(x,y)*2);}}

My understanding of the brief was that you only need a function, not a whole program.

T-SQL, 158
IF PATINDEX('%[^UDLR]%', @s)=0 select 2*sqrt(power(LEN(REPLACE(@s,'U',''))-LEN(REPLACE(@s,'D','')),2)+power(LEN(REPLACE(@s,'L',''))-LEN(REPLACE(@s,'R','')),2))

The @s is the input string of varchar(max) type

ES6, 77 69
Definition:
f=s=>{u=d=l=r=0;for(c of s)eval(c+'++');return 2*Math.hypot(u-d,l-r)}

Usage:
>>> f('uuuudrrrl')
7.211102550927979
>>> f( 'uuuudrrrl'.split('') )
7.211102550927979

Accepts string OR array (lowercase)
Doesn't use imaginary numbers
Would not have been possible just 3 days before OP posted the question; that is, it only runs in Firefox 27+ (and maybe also Chrome with experimental stuff enabled, haven't tested :)!!

(Inspired partially by Boann's answer.)

I really wanna do something tricky to get rid of the return, like turn the whole thing into a boolean expression that just gets evaluated and returned automagically, but I'm not sure there's a way to do this unless I can replace the for statement with some expression (an arrow function body containing statements require the brackets and the explicit return, bodies that are just expressions don't)..

JavaScript - 142 characters - no eval()
function r(a){return Math.sqrt(Math.pow(a.match(/u/g).length-a.match(/d/g).length,2)+Math.pow(a.match(/l/g).length-a.match(/r/g).length,2))*2}

where a is a string like 'uudrrl'
use like this -
a='uudrrl'
r(a)

Test in browser console.
var x = "luluurrrrurd"
r(x)
8.48528137423857

C# - 90 characters
Fresh from LINQPad.
int x=0,y=0;input.Max(i=>i==85?y++:i==82?x++:i==68?y--:x--);(Math.Sqrt(x*x+y*y)*2).Dump();

Where input is a valid string.
>string input = "LULUURRRRURD";

>8.48528137423857

Jelly, 10 9 bytes
O:3 ı*SḤA

Try it online!
I fiddled around with other functions to see if I could get rid of the space by finding a different one-byte dyad that would take a two-digit number on the left rather than the right, but it turned out that : doesn't need two digits to produce the desired values.
O            Codepoints of the input
 :3          floor divided by 3.
    ı*       Raise sqrt(-1) to the power of each,
      S      sum,
       Ḥ     double,
        A    and take the absolute value.

J, 29 characters
+:+&.*:/-/_2[\#/.~/:~'ruld'i.

Only works with lower case directions and any characters other than r, u, l, and d will cause it to give a wrong answer.
Usage:
   +:+&.*:/-/_2[\#/.~/:~'ruld'i.'uuuudrrrl'
7.2111

Explanation:
'ruld'i.'uuuudrrrl' The dyadic form of i. finds the index of items from the right argument in the left argument. In this case:
   'ruld'i.'uuuudrrrl'
1 1 1 1 3 0 0 0 2

/:~ sorts this list into ascending order:
   /:~'ruld'i.'uuuudrrrl'
0 0 0 1 1 1 1 2 3

#/.~ counts the number of occurrences of each number:
   #/.~/:~'ruld'i.'uuuudrrrl'
3 4 1 1

_2[\ chops it into 2 rows:
   _2[\#/.~/:~'ruld'i.'uuuudrrrl'
3 4
1 1

-/ subtracts the bottom from the top
   -/_2[\#/.~/:~'ruld'i.'uuuudrrrl'
2 3

+&.*: borrows a trick from another J answer I saw this morning, and squares the items, then sums them, then  performs a square root. See under &. documentation:
   +&.*:/-/_2[\#/.~/:~'ruld'i.'uuuudrrrl'
3.60555

+: doubles the result:
   +:+&.*:/-/_2[\#/.~/:~'ruld'i.'uuuudrrrl'
7.2111

Matlab, 51 characters
My Matlab submission, works only with captial letters. This was a fun one! The hardest part was converting the string into an array of complex numbers to be summed.
Function:
f=@(s)abs(sum(fix((s-76.5)/8.5)+((s-79)*i/3).^-99))

Usage:
>> f=@(s)abs(sum(fix((s-76.5)/8.5)+((s-79)*i/3).^-99))
>> f('UURDL')
ans =

     1
>>

Javascript, 136
function z(a){var x=a.split('u').length-a.split('d').length;var y=a.split('r').length-a.split('l').length;return Math.sqrt(x*x+y*y)*2;};

Example:
document.write(z('uuuudrrrwl'));
7.211102550927978

JavaScript, 89
function f(a){U=D=L=R=0;for(d in a)eval(a[d]+'++');return 2*Math.sqrt((U-=D)*U+(L-=R)*L)}

Example:
<script>
document.write(f(['U', 'U', 'U', 'U', 'D', 'R', 'R', 'R', 'L']));
</script>

>7.211102550927978

C, 120
float d(char *p){int v=0,h=0;while(*p){v+=*p=='U'?1:*p=='D'?-1:0,h+=*p=='R'?1:*p=='L'?-1:0,++p;}return 2*sqrt(v*v+h*h);}

d("LULUURRRRURD") -> 8.485281

JavaScript (no ES6, no eval) - 131
f=function(h){for(i=0,a=[0,,0,0,0];i<h.length;++i)++a[(h.charCodeAt(i)>>2)-25];x=a[0]-a[4];y=a[2]-a[3];return Math.sqrt(x*x+y*y)*2}

Test:

console.log(f('uuuudrrrl'));     // 7.211102550927978
console.log(f('luluurrrrurd'));  // 8.48528137423857

Perl 5 -p, 44 bytes
$_=2*sqrt((y/R//-y/L//)**2+(y/U//-y/D//)**2)

Try it online!

Befunge-93 (65)
It has 65 non-whitespace characters (217 with whitespace, though that can be reduced by a more compact layout (for 69/176 chars)). It takes some liberality with the output format, but is undeniably accurate. Doesn't seem worth the effort to implement/steal a square root implementation.
v                  >$:*\:*+88*4*5-2.,.@
               >3-:|
           >6-:|
       >8-:|
>~"D"-:|
       $   $   $   $
           \   \
       1   1   1   1
       -   -   +   +
           \   \
^      <   <   <   <

echo 'UUDLLUU' | ./befungee.py ../man outputs 2√13 (actually implementation seems to have issue with the extended ASCII though).

authors: Bob Jarvis - Слава Україні

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/