# Death By Shock Probe: That's a lot of dice

In the webcomic Darths & Droids, Pete, who plays R2-D2 in the fictional roleplaying campaign around which the comic is based, once claims (warning: potential spoilers in the linked comic) that, with the Lost Orb of Phanastacoria rigged up to his shock probe, he can now dish out a whopping 1048576d4 of damage. (The GM has neither confirmed nor denied this.) Since it should be reasonably obvious that almost no one will actually have the patience to roll that many dice, write a computer program to do it for him, outputting the total value rolled in some reasonable format. Entries will be ranked by program size (shortest program, by byte count, wins), both overall and per-language, with run time breaking ties. Answer may be either a full program or a function definition.

# Scores Per-Language

Pyth

Maltysen - 8 bytes*

Jakube - 10 bytes

APL

Alex A - 10 bytes

CJam

Optimizer - 11 bytes

J

ɐɔıʇǝɥʇuʎs - 12 bytes **

Clip10

Ypnypn - 12 bytes **

K

JohnE - 13 bytes

Ti-84 BASIC

SuperJedi224 - 17 bytes*

R

MickyT - 23 bytes

OCTAVE/MATLAB

Oebele - 24 bytes

PARI/GP

Charles - 25 bytes **

Wolfram/Mathematica

LegionMammal978 - 27 bytes

Perl

Nutki - 29 bytes

AsciiThenAnsii - 34 bytes

Ruby

Haegin - 32 bytes **

ConfusedMr_C - 51 bytes **

Commodore Basic

Mark - 37 bytes **

PHP

Ismael Miguel - 38 bytes

VBA

Sean Cheshire - 40 bytes **

PowerShell

Nacht - 41 bytes **

Javascript

Ralph Marshall - 41 bytes

edc65 - 54 bytes (Requires ES6 functionality not available in all browsers.)

Lua

cryptych - 51 bytes

Java

RobAu - 52 bytes **

Geobits - 65 bytes

C

Functino - 57 bytes

Python

CarpetPython - 58 bytes

Postgre/SQL

Andrew - 59 bytes **

Swift

Skrundz - 69 bytes

GoatInTheMachine - 81 bytes

Zeta - 73 bytes **

ActionScript

Brian - 75 bytes **

><>

ConfusedMr_C - 76 bytes

GO

Kristoffer Sall-Storgaard - 78 bytes

C#

Brandon - 91 bytes **

Andrew - 105 bytes

Ewan - 148 bytes

Scratch

SuperJedi224 - 102 bytes

C++

Michelfrancis Bustillos - 154 bytes

Polyglots

Ismael Miguel (Javascript/ActionScript2) - 67 bytes

# Top 10 Overall

Maltysen
Alex A
Jakube
Optimizer
ɐɔıʇǝɥʇuʎs/Ypnypn (order uncertain)
JohnE
SuperJedi224
MickyT
Oebele

Warning- entries marked with a * are VERY SLOW.

Programmed marked ** I have not yet been able to properly test

• Wait, do I have to give the sum of the dice roll or just all the rolls in a list? – Maltysen Apr 30 '15 at 1:58
• Your question, as it stands, will likely be criticized for being unclear or being overly broad. It would be very helpful if you described in specific, objective terms how programs will be scored and what methods programs should have available to them. Also, the notation of 1048576d4 may be unclear to some users. It would be helpful to provide a description of precisely what should be computed, and any guidelines that must be followed. – BrainSteel Apr 30 '15 at 2:05
• This problem can be done too quickly to be a good time trial. – isaacg Apr 30 '15 at 2:57
• You could try your hand at making a stack snippet leaderboard to avoid having to manually keep the list of submissions up to date. – Alex A. Apr 30 '15 at 14:32
• I absolutely love this title. – ASCIIThenANSI Apr 30 '15 at 22:19

# Pyth - 9 8 bytes

Uses obvious simple method of summation of randint. Took me minute to realize 1048576 was 2^20, now I feel really stupid. Thanks to @Jakube for saving me a byte by pointing out 2^20 = 4^10.

smhO4^4T

The runtime is horrible, it has yet to finish on my computer, so there is no point running it online so here is the 2^10 one: Try it online here.

s        Summation
m       Map
h      Incr (accounts for 0-indexed randint)
O4    Randint 4
^4T    Four raised to ten
• 8 bytes are possible. 2^20 = 4^10 – Jakube Apr 30 '15 at 9:34
• @Jakube thanks for the tip :) – Maltysen Apr 30 '15 at 16:35
• This finishes immediately for me. – Carcigenicate May 2 '15 at 0:16
• @Carcigenicate are you talking about the link I gave? That's the modified one, only sums 1024d4. – Maltysen May 2 '15 at 0:35
• @Maltysen Whoops, sorry. Ya, that's it. – Carcigenicate May 2 '15 at 0:36

# Perl - 48443739 34 bytes

$-+=rand(4)+1for(1..2**20);print$-

Prints the sum without a trailing newline.
Saved 4 bytes by substituting for 2**20 (thanks Maltysen) and removing quotes around print.
Saved another 7 bytes by rearranging the code (thanks Thaylon!)
Lost 2 bytes because my old code generated 0-4 (it should be 1-4).
Once again, saved 5 bytes thanks to Caek and nutki.

Ungolfed, properly written code:

my $s = 0$s += int( rand(4) + 1 ) for (1 .. 2**20);
print "$s"; • It was a little hard to get a timer hooked up, but I eventually got it working. – SuperJedi224 Apr 30 '15 at 2:35 • Since we dont care about warnings ...$s+=int rand(5)for(1..2**20);print$s – Thaylon Apr 30 '15 at 14:11 • int(rand(5)) returns range 0 to 4 while d4 should be 1 to 4. – nutki Apr 30 '15 at 19:19 • @nutki OK, thanks. I've edited that in now. – ASCIIThenANSI Apr 30 '15 at 20:05 •$s+=int rand(4)+1for(1..2**20);print$s Removing the parenthesis for int also works for me, to save a stroke. – Caek May 1 '15 at 5:03 # APL, 11 10 bytes +/?4⍴⍨2*20 This just takes the sum of an array of 220 = 1048576 random integers between 1 and 4. +/ ⍝ Reduce by summing a ? ⍝ random integer 4⍴⍨ ⍝ array with values between 1 and 4 2*20 ⍝ of length 2^20 You can benchmark this on TryAPL by printing the timestamp before and after. It takes about 0.02 seconds. Saved a byte thanks to marinus and FUZxxl! • One and 5??? A d4 can give 1, 2, 3 or 4. You can't get 5. – Loren Pechtel Apr 30 '15 at 3:59 • @LorenPechtel: Sorry, my bad. Thanks for pointing that out. It's fixed now. I have tired brain. – Alex A. Apr 30 '15 at 4:02 • Save a byte: +/?4⍴⍨2*20 – marinus Apr 30 '15 at 9:35 • Small improvement: use +/?4⍴⍨2*20 instead. – FUZxxl Apr 30 '15 at 11:50 • Incidtenally, this answer is not golfed in any way: It would be written exactly the same way in production APL code. – FUZxxl Jul 11 '15 at 21:13 # Ti-84 Basic, 17 bytes Total footprint - Size of program header = 17 bytes Run Time: Unknown, estimated at 5-6 hours based on performance for smaller numbers of rolls (so, basically, not very good) Σ(randInt(1,4),A,1,2^20 • +1 for making it run on a TI-84. I guess time isn't a problem here, those are 30-40 year-old calculators by now. – ASCIIThenANSI Apr 30 '15 at 14:15 • I presume there's a function for sampling a normal distribution rather than a uniform one? Should be much quicker. – Ben Voigt Apr 30 '15 at 18:25 • @BenVoigt: Since this is meant to simulate the rolling of dice, a normal distribution is not appropriate; it would have to be uniform. – Alex A. Apr 30 '15 at 19:47 • @AlexA.: Central Limit Theorem provides that the sum of many uniform dice is indistinguishable from a normal distribution. So it depends on how pedantic we are about "simulating rolling". – Ben Voigt Apr 30 '15 at 20:34 • @M.I.Wright, I thought it was just for communication. At least the one I've got uses AAA batteries. – Arturo Torres Sánchez Apr 30 '15 at 21:35 # R, 322423 21 bytes Edit: Got rid of the as.integer and used integer division %/%. Speed it up slightly. Thanks to Alex A for the sample tip ... and Giuseppe for removing the r= sum(sample(4,2^20,T)) Tested with i = s = 0 repeat { i = i + 1 print(sum(sample(4,2^20,r=T))) s = s + system.time(sum(sample(4,2^20,r=T)))[3] if (i == 10) break } print (s/10) Outputs [1] 2621936 [1] 2620047 [1] 2621004 [1] 2621783 [1] 2621149 [1] 2619777 [1] 2620428 [1] 2621840 [1] 2621458 [1] 2620680 elapsed 0.029 For pure speed the following completes in microseconds. However I'm not sure I've got my logic correct for it. The results appear consistent with the random method. Shame it's a longer length. sum(rmultinom(1,2^20,rep(1,4))*1:4) Here's a timing run I did on my machine system.time(for(i in 1:1000000)sum(rmultinom(1,2^20,rep(1,4))*1:4)) user system elapsed 7.330000000000040927262 0.000000000000000000000 7.370000000000345607987 • You can save a couple bytes by using sample() in place of runif(), i.e. sum(sample(4,2^20,r=T)). – Alex A. Apr 30 '15 at 4:09 • Just did some benchmarking on my computer and sample() is actually faster too! – Alex A. Apr 30 '15 at 4:26 • @AlexA. Thanks will test and change when I get close to a computer – MickyT Apr 30 '15 at 6:05 • not to necro this or anything but you don't need r=T, just T is fine for replacement. – Giuseppe Jun 12 '17 at 21:12 • @Giuseppe, thanks .. this really was an old one – MickyT Jun 12 '17 at 21:33 # Python 2, 58 bytes We get 1048576 random characters from the operating system, take 2 bits of each, and add them up. Using the os library seems to save a few characters over using the random library. import os print sum(1+ord(c)%4 for c in os.urandom(1<<20)) This takes about 0.2 seconds on my PC. # CJam, 12 11 bytes YK#_{4mr+}* This is pretty straight foward: YK e# Y is 2, K is 20 # e# 2 to the power 20 _ e# Copy this 2 to the power 20. The first one acts as a base value { }* e# Run this code block 2 to the power 20 times 4mr e# Get a random int from 0 to 3. 0 to 3 works because we already have e# 2 to the power 20 as base value for summation. + e# Add it to the current sum (initially 2 to the power 20) But the beauty of this is that its really fast too! On my machine (and using the Java compiler) it takes on an average of 70 milliseconds. The online version takes around 1.7 seconds on my machine. Update: 1 byte saved thanks to DocMax • The online version is taking about 6 seconds from the computers here, but that's probably just the network and/or the macbooks the school insists on using. I'll try again when I get home. – SuperJedi224 Apr 30 '15 at 15:47 • @SuperJedi224 The online version is all in JavaScript, does not make any network calls. You can download the Java version and run it using the instructions on the website. – Optimizer Apr 30 '15 at 15:48 • Unless I am missing something (which is sadly too common with CJam and me), instead of seeding with 0 and adding 1 for 2^20 runs, seed with 2^20 to save 1 byte: YK#_{4mr+}* – DocMax Apr 30 '15 at 19:34 • @DocMax You are right. Thanks! – Optimizer Apr 30 '15 at 19:36 • +1; I was going to post this exact answer (except with 4A# instead of YK#), but you beat me to it. :) – Ilmari Karonen Apr 30 '15 at 21:00 # JavaScript (ES6), 54 bytes Average time < 100 msec. Run snippet to test (in Firefox) // This is the answer f=t=>(i=>{for(t=i;i--;)t+=Math.random()*4|0})(1<<20)|t // This is the test test(); function test(){ var time = ~new Date; var tot = f(); time -= ~new Date; Out.innerHTML = "Tot: " + tot + " in msec: " + time + "\n" + Out.innerHTML; } <button onclick="test()">Repeat test</button><br> <pre id=Out></pre> Explanation With no statistical package built-in, in Javascript the shortest way to obtain the sum of 1 million random number is to call random() for a million times. So simply f=()=>{ var t = 0, r, i for (i=1<<20; i--; ) { r = Math.random()*4 // random number between 0 and 3.9999999 r = r + 1 // range 1 ... 4.999999 r = r | 0 // truncate to int, so range 1 ... 4 t = t+r } return t } Now, adding 1 for a million times is exactly the same than adding 1 million, or even better, start the sum with 1 million and then add the rest: f=()=>{ var t, r, i for (t = i = 1<<20; i--; ) { r = Math.random()*4 // random number between 0 and 3.9999999 r = r | 0 // truncate to int, so range 0 ... 3 t = t+r } return t } Then golf, drop the temp variable r and drop the declaration of local variables. t is a parameter, as one is needed to shorten the declaration of f. i is global (bad thing) f=t=>{ for(t=i=1<<20;i--;) t+=Math.random()*4|0 return t } Then find a way to avoid 'return' using a nameless inner function. As a side effect, we gain another parameter so no globals used f=t=>( (i=>{ // start inner function body for(t=i;i--;)t=t+Math.random()*4|0 // assign t without returning it })(1<<20) // value assigned to parameter i | t // the inner function returns 'undefined', binary ored with t gives t again ) // and these open/close bracket can be removed too • Doesn't work in chrome. About to test in FF. – SuperJedi224 Apr 30 '15 at 21:31 • Of course. Chrome is ES5 – edc65 Apr 30 '15 at 21:31 • It has some ES6 support (most of which is only available by enabling experimental javascript from chrome:\\flags), but does not yet support arrow functions – SuperJedi224 Apr 30 '15 at 21:32 # Perl, 29 Generates a table of the required length. print~~map{0..rand 4}1..2**20 • I'm getting a syntax error on this one. – SuperJedi224 Apr 30 '15 at 22:03 • This needs a new enough version of Perl (the smartmatch operator was introduced in 5.10.1, and I think it wasn't made available by default until later). – Mark Apr 30 '15 at 23:31 • ~~ is not a smartmatch, just a double bit inversion to force scalar context. A one character longer way would be print$x=map.... Maybe on newer versions it warns because of ambiguity with smartmatch, but it does seem to work without warnings on my system and in here: ideone.com/LAIWzq – nutki May 1 '15 at 10:50
• Yep, it works on IDEone. I'll give it to you. – SuperJedi224 May 1 '15 at 13:49

# J (12 bytes, about 9.8 milliseconds)

+/>:?4$~2^20 I suspect this is mostly memory bandwith-limited: I can't even get it to max out a single core... You can test this with the following code: timeit =: 13 : '(1000 * >./ ($/x) 6!:2"0 1 y)'

Usage:

$ghci sourcefile.hs ghci> f 2622130 C#: 105 bytes using System.Linq;class C{int D(){var a=new System.Random();return new int[1<<20].Sum(i=>a.Next(1,5));}} • Nice, I like this even if it's two times wrong. It's 1<<20, not 2<<20. And the second parameter of Random.Next is The *exclusive* upper bound of the range so it should be 5 – edc65 May 1 '15 at 22:04 • @edc65 Thanks for catching those errors. I have updated the answer. – Andrew May 1 '15 at 22:08 • You could save 9 chars by eliminating a and moving the new System.Random() inside of the Sum. Sure, it will create a new Random every time, but who cares as long as it gives a result? – LegionMammal978 May 2 '15 at 1:28 • @LegionMammal978 if you create a new Random again and again, the result is mostly non-random – edc65 May 3 '15 at 20:24 • @edc65 That is why I didn't go that route. I haven't had a chance to test what happens if I followed the suggestion. – Andrew May 3 '15 at 20:34 # PHP, 38 37 bytes This uses a very simple idea: sum them all! Also, I've noticed that 1048576 is 10000000000000000000 in binary, equivalent to 1<<20. Here's the code: while($i++<1<<20)$v+=rand(1,4);echo$v

Test in your browser (with VERY LITTLE changes):

$i=$v=0;while($i++<1<<20)$v+=rand(1,4);printf($v); //'patch' to make a TRUE polyglot, to work in JS if('\0'=="\0")//this will be false in PHP, true in JS { //rand function, takes 2 parameters function rand($m,$n){ return ((Math.random()*($n-$m+1))+$m)>>0;

/*
*returns an integer number between $m and$n
*example run, with rand(4,9):
*(Math.random()*(9-4+1))+4
*
*if you run Math.random()*(9-4+1),
*it will returns numbers between 0 and 5 (9-4+1=6, but Math.random() never returns 1)
*but the minimum is 4, so, we add it in the end
*this results in numbers between 0+4 and 4+5
*
*/

}

//for this purpose, this is enough
function printf($s){ document.write($s);
}
}

/*
*Changes:
*
*- instead of echo, use printf
*    printf outputs a formatted string in php
*    if I used echo instead, PHP would complain
*- set an initial value on $i and$v
*    this avoids errors in Javascript
*
*/

$i=$v=0;while($i++<1<<20)$v+=rand(1,4);printf($v); All the changes in the code are explained in comments. • You can remove the ; after echo$v – Martijn May 1 '15 at 13:24
• @Martijn I left it there because most of the time PHP complains about it. But I have removed it now. It works on sandbox.onlinephpfunctions.com and that's enough. – Ismael Miguel May 1 '15 at 18:20

# Mathematica, 30 27 bytes

Tr[RandomInteger[3,2^20]+1]

Mathematica has quite long function names...

# C, 57 bytes

main(a,b){for(b=a=1<<20;a--;b+=rand()%4);printf("%d",b);}

This code works... once. If you ever need to roll those dice again, you'll need to put srand(time(0)) in there, adding 14 bytes.

• Why would you need to add srand(time(0))? (Sorry, I don't use C.) – ASCIIThenANSI Apr 30 '15 at 16:27
• @ASCIIThenANSI Many implementations of C's rand seed it to the same value every run. srand seeds the RNG, and time(0) gets the current time in seconds since 1970. – Functino Apr 30 '15 at 16:31
• If you initialize a=b=1<<20 then you can skip 1+, this saves 4 bytes. – nutki Apr 30 '15 at 19:23
• Also, int before main is not required. – nutki Apr 30 '15 at 19:45
• Hint to anybody doing t=0, then t=t (...) +1 for 1048576 times: think again! (see my answer, eventually) – edc65 Apr 30 '15 at 20:38

# PostgreSQL, 59 bytes

select sum(ceil(random()*4)) from generate_series(1,1<<20);

I'll admit to the slight problem that random() could, in theory, produce exactly zero, in which case the die roll would be zero.

• You don't really need the ; to terminate the query since it is the only one – MickyT May 3 '15 at 21:18

# Ruby, 32 bytes

(1..2**20).inject{|x|x-~rand(4)}

(1..2**20).inject(0) do |x|
x + rand(4) + 1
end

It creates a range from 1 to 1048576 and then iterates over the block that many times. Each time the block is executed the value from the previous iteration is passed in as x (initially 0, the default for inject). Each iteration it calculates a random number between 0 and 3 (inclusive), adds one so it simulates rolling a d4 and adds that to the total.

On my machine it's pretty fast to run (0.25 real, 0.22 user, 0.02 sys).

If you've got Ruby installed you can run it with ruby -e 'p (1..2**20).inject{|x|x+rand(4)+1}' (the p is necessary to see the output when run in this manner, omit it if you don't care for that or just run it inside IRB where the result is printed to the screen for you). I've tested it on Ruby 2.1.6.

Thanks to histocrat for the bit twiddling hack that replaces x + rand(4) + 1 with x-~rand(4).

• Could you explain how it works? – ASCIIThenANSI Apr 30 '15 at 16:41
• The first online interpreter I could find that actually wants to load claims that the method rand() doesn't exist. I'll try to find another one. – SuperJedi224 May 1 '15 at 13:39
• Okay, I found one that works. – SuperJedi224 May 1 '15 at 13:45
• Bit twiddling hack: x-~rand(4) is equivalent to x+rand(4)+1. – histocrat May 2 '15 at 18:53
• Also, you can replace 2**20 with 4e10. – histocrat May 2 '15 at 18:53

## PARI/GP, 25 bytes

Really, no need for golfing here -- this is the straightforward way of doing the calculation in GP. It runs in 90 milliseconds on my machine. Hoisting the +1 saves about 20 milliseconds.

sum(i=1,2^20,random(4)+1)

Just for fun: if one were optimizing for performance in PARI,

inline long sum32d4(void) {
long n = rand64();
// Note: __builtin_popcountll could replace hamming_word if using gcc
return hamming_word(n) + hamming_word(n & 0xAAAAAAAAAAAAAAAALL);
}

long sum1048576d4(void) {
long total = 0;
int i;
for(i=0; i<32768; i++) total += sum32d4();
}

has a very small total operation count -- if xorgens needs ~27 cycles per 64-bit word (can anyone verify this?), then a processor with POPCNT should take only about 0.5 cycle/bit, or a few hundred microseconds for the final number.

This should have close-to-optimal worst-case performance among methods using random numbers of similar or higher quality. It should be possible to greatly increase average speed by combining cases -- maybe a million rolls at a time -- and selecting with (essentially) arithmetic coding.

# Javascript, 55535047 41 bytes

for(a=i=1<<20;i--;)a+=(Math.random()*4)|0

I didn't realize that non-random numbers were a known irritant, so I figure that I ought to post a real solution. Meant no disrespect.

Commentary: as noted by others above you can skip the +1 to each roll by starting off with the number of rolls in your answer, and by not having to write a=0,i=1<<20 you save two bytes, and another 2 because you don't add +1 to each roll. The parseInt function does the same thing as Math.floor but is 2 characters shorter.

• Note that this answer is completely different from the one originally commented on by SuperJedi224 and @Andrew – Ralph Marshall May 2 '15 at 19:15
• You can remove both brackets and the last semicolon (and only the last one) to cut down a few further characters. Also, the current version is only 50 characters, not 52. – SuperJedi224 May 2 '15 at 19:49
• SuperJedi - thanks for the suggestions. I thought I'd tried it without the brackets only to run into problems, but perhaps I had a different problem. In any case, I think this is about as good as it's going to get. – Ralph Marshall May 3 '15 at 1:31
• a+=parseInt(Math.random()*4) may be shortened to a+=1+Math.random()*4&7. The 1+ is only if you care if it rolls 0 or not. – Ismael Miguel May 3 '15 at 17:45
• You can golf it down to this: for(a=i=1<<20;i--;)a+=(Math.random()*4)|0, that's only 41 bytes – SuperJedi224 May 30 '15 at 18:18

## Clip 10, 12 bytes

r+m[)r4}#WT

#4T    .- 4^10 = 1048576             -.
m[   }       .- that many...               -.
)r4        .-          ...random numbers -.
r+             .- sum                        -.

It takes approximately 0.6 seconds to run on my machine.

# Go, 78 bytes

## Golfed

import."math/rand";func r()(o int){for i:=2<<19;i>=0;i--{o+=Intn(4)+1};return}

Still working on it

Run online here http://play.golang.org/p/pCliUpu9Eq

• Unfortunately, the golang.org playground doesn't implement the time operations properly and the repl.it one doesn't want to load right now. I'll see what I can do about it this afternoon. – SuperJedi224 Apr 30 '15 at 14:12

# Go, 87 bytes

## Naive solution

import"math/rand";func r(){o,n:=0,2<<19;for i:=0;i<n;i++{o+=rand.Intn(4)};println(o+n)}

Run online here: http://play.golang.org/p/gwP5Os7_Sq

Due to the way the Go playground works you have to manually change the seed (time is always the same)

## Commodore Basic, 37 bytes

1F┌I=1TO2↑20:C=C+INT(R/(1)*4+1):N─:?C

PETSCII substitutions: = SHIFT+E, / = SHIFT+N, = SHIFT+O

Estimated runtime based on runs with lower dice counts: 4.25 hours.

It's tempting to try to golf off two bytes by making C an integer, getting implicit rounding of the random numbers. However, the range on integers in Commodore Basic is -32678 to 32767 -- not enough, when the median answer is 2621440.

## PowerShell, 41 37 bytes

1..1mb|%{(get-random)%4+1}|measure -s

Took my machine 2 minutes 40 seconds

## Ruby, 51 47 chars

x=[];(2**20).times{x<<rand(4)+1};p x.inject(:+)

I looked at all of the answers before I did this, and the sum(2**20 times {randInt(4)}) strategy really stuck out, so I used that.

## ><>, 76 chars

012a*&>2*&1v
|.!33&^?&:-<
3.v < >-:v >
vxv1v^<;3
1234    n+
>>>> >?!^^

I'm not sure if this one works, because my browser crashed when I tried to test it, but here's the online interpreter.

• I'll give you a +1 for the ><> answer. – SuperJedi224 Jul 8 '15 at 0:43

# Swift, 64 bytes

Nothing clever, golfing in Swift is hard...

func r()->Int{var x=0;for _ in 0..<(2<<19) {x+=Int(arc4random()%4)+1;};return x;}

Version 2 (too late)

var x=0;for _ in 0..<(2<<19){x+=Int(arc4random()%4)+1;};print(x)

# Java (Java 8) - 52

int f(){return new Random().ints(1<<20,1,5).sum();}