| Bytes | Lang | Time | Link |
|---|---|---|---|
| 055 | JavaScript ES6 | 250310T223847Z | Steve Be |
| 016 | APLNARS | 250310T090619Z | Rosario |
| 063 | Desmos | 250310T034833Z | DesmosEn |
| 180 | Pascal | 250306T090015Z | Kai Burg |
| 009 | Jelly | 201127T181550Z | Unrelate |
| 044 | Perl 5 p | 201127T172832Z | Xcali |
| 136 | Javascript | 140206T191420Z | Xin |
| 090 | C# | 140207T210136Z | tdink |
| 142 | JavaScript | 140207T120418Z | rahulroy |
| 131 | JavaScript no ES6 | 140207T170042Z | iefserge |
| 069 | ES6 | 140206T225831Z | Noyo |
| 120 | C | 140206T232215Z | warrenm |
| 045 | Julia | 140206T225816Z | gggg |
| 044 | perl6 | 140206T213830Z | Ayiko |
| 158 | TSQL | 140206T193648Z | duanxn |
| 089 | JavaScript | 140206T200802Z | Boann |
| 067 | PHP | 140206T185953Z | Boann |
| 048 | Python 2.7 | 140206T085029Z | Abhijit |
| 067 | Ruby 1.9+ | 140206T181056Z | daniero |
| 049 | Mathematica | 140206T041631Z | DavidC |
| nan | Java | 140206T165107Z | James We |
| 051 | Matlab | 140206T150741Z | Hannesh |
| 049 | k | 140206T084846Z | skeevey |
| 056 | R | 140206T084206Z | plannapu |
| 017 | J | 140206T102953Z | Howard |
| 029 | APL | 140206T101159Z | marinus |
| 065 | Befunge93 | 140206T085700Z | Joel Bos |
| 029 | J | 140206T093639Z | Gareth |
| 065 | Python 2.7 | 140206T031015Z | user8777 |
JavaScript (ES6), 55 characters
With a bit of help from 14m2.
s=>(u=d=l=r=0,s.map(l=>this[l]+=2),Math.hypot(u-d,r-l))
Javascript (ES6), 58 characters
Borrowing a few ideas from others. Did not know Math.hypot was a thing!
s=>(u=d=l=r=0,s.map(l=>window[l]++),Math.hypot(u-d,r-l)*2)
JavaScript (ES6), 80 characters
s=>(x=y=0,s.map(l=>l=='u'?y++:l=='d'?y--:x+={l:-1,r:1}[l]),Math.sqrt(x*x+y*y)*2)
Nothing very clever. Takes an array of individual characters as input.
APL(NARS), 16 chars
2×∣+/1i*'ULDR'⍳⎕
Copy the idea of make the powers of the immaginary unity 0J1 or 1i in corrispondence of array 'ULDR'. It is start from x y = 0 0, and each result of partial sum represent the point it arrived. The last result of the partial sum is the point x y of end, of that point I calculate the distance of the start 0 0, and multiplicate that distance by 2.
2×∣+/1i*'ULDR'⍳⎕
⎕:
'LULUURRRRURD'
8.485281374
Desmos, 63 bytes
l=(-1,0)
r=(1,0)
u=(0,1)
d=(0,-1)
f(l)=2distance(l.total,(0,0))
f takes an array of direction vectors as an input, sums them, then outputs double the distance of the sum to (0,0).
Pascal, 180 B
This submission requires a processor compliant with Extended Pascal level 1 as laid out in ISO standard 10206, in particular the complex number support.
function F(S:array[A..Z:integer]of char):real;var P:complex;I:integer;begin
P:=0;for I:=A to Z do
P:=P+cmplx(ord(S[I]='R')-ord(S[I]='L'),ord(S[I]='U')-ord(S[I]='D'));F:=2*abs(P)end
−15 B if you do not insist on having a function but a complete program is acceptable, too.
It is otherwise the same algorithm.
program M(input,output);var P:complex;S:char;begin
P:=0;while not EOF do begin
read(S);P:=P+cmplx(ord(S='R')-ord(S='L'),ord(S='U')-ord(S='D'))end;write(2*abs(P))end.
Explained:
{ By listing a `program` parameter of the spelling `input`,
there’s an implicit `reset(input)` which implies a `get(input)`. }
program richBritishPeopleProblem(input, output);
var
{ `cmplx(real_part, imaginary_part)` returns a `complex` value.
Here, `polar(radius, argument)` would’ve been another option. }
position: complex value cmplx(0.0, 0.0);
step: char;
begin
while not EOF(input) do
begin
{ `Read(input, step)` is short for `step ≔ input↑; get(input)`
except that `read` cannot read past end‐of‐line sequences. }
read(input, step);
position ≔ position + cmplx(
{ The built‐in function `ord` converts a Boolean value
into an `integer` value. The `integer` value is then
automatically promoted to `real` because `cmplx` wants
`real` arguments. }
ord(step = 'R') − ord(step = 'L'),
ord(step = 'U') − ord(step = 'D')
)
end;
{ `abs` also returns the magnitude of a complex number.
This is shorter than `sqrt(x*x+y*y)` even accounting
for the additional declaration and function calls. }
writeLn(output, 2 × abs(position))
end.
The constants U, R, D and L are to be interpreted as north, east, south and west respectively, but British rich people aren’t that smart.
Jelly, 10 9 bytes
O:3 ı*SḤA
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.
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
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
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
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
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.)
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
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.
perl6: 44 chars
2*abs [+] i <<**>>%(<U R D L>Z ^4){get.comb}
get.combgets 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 bei[+]sums all elements of a list,abstakes the modulus for complex numbers
Yes, I removed all possible spaces.
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
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
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)
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
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
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
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);}}
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
>>
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
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).
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 ofj.+/sums up the single steps2*|two times the modulus
Example:
> 2*|+/0j1^'urdl'i.'uuuudrrrl'
7.2111
APL (29)
{|+/2 0j2×-⌿2 2⍴+/'URDL'∘.=⍵}
e.g.
{|+/2 0j2×-⌿2 2⍴+/'URDL'∘.=⍵} 'UUUUDRRRL'
7.211102551
Explanation:
+/'URDL'∘.=⍵: see how often the charactersURDLoccur in the argument-⌿2 2⍴: subtract theUvalue from theDvalue, and theRvalue from theLvalue2 0j2×: multiply the vertical value by2and the horizontal value by2i+/: sum|: magnitude
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).
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
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.