[Question]
  [
In the webcomic [Darths & Droids](http://darthsanddroids.net/episodes/0001.html), Pete, who plays R2-D2 in the fictional roleplaying campaign around which the comic is based, [once claims](http://darthsanddroids.net/episodes/1174.html) (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](http://en.wikipedia.org/wiki/Dice_notation) 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
**Haskell**
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
  
[Answer]
# 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](http://pyth.herokuapp.com/?code=smhO4%5E2T&debug=0).
```
s        Summation
 m       Map
  h      Incr (accounts for 0-indexed randint)
   O4    Randint 4
  ^4T    Four raised to ten
```
[Answer]
# Perl - ~~48~~ ~~44~~ ~~37~~ ~~39~~ 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";
```
[Answer]
# 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](http://tryapl.org/?a=%u2395ts%u22C4+/%3F4%u2374%u23682*20%u22C4%u2395ts&run) by printing the timestamp before and after. It takes about 0.02 seconds.
Saved a byte thanks to marinus and FUZxxl!
[Answer]
# 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
```
[Answer]
# R, ~~32~~ ~~24~~ ~~23~~ 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 
```
[Answer]
# 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.
[Answer]
# 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](https://sourceforge.net/p/cjam/wiki/Home/)) it takes on an average of 70 milliseconds.
The [online version](http://cjam.aditsu.net/#code=esYK%23_%7B4mr%2B%7D*es%40-p) takes around 1.7 seconds on my machine.
*Update*: 1 byte saved thanks to DocMax
[Answer]
# 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
```
[Answer]
# Perl, 29
Generates a table of the required length.
```
print~~map{0..rand 4}1..2**20
```
[Answer]
# [J](http://jsoftware.com/) (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)'
   4 20 timeit '+/>:?4$~2^20'
9.90059
```
This runs it in 4 groups of 20 trails, and returns the number of milliseconds of the avarage time in the quickest group. An interpreter can be found [here](http://www.jsoftware.com/download/j803/install/).
[Answer]
# Pyth, 10 bytes
```
u+GhO4^4TZ
```
This has slightly more bytes than @Maltysen's Pyth solution. But it runs in 8.5 seconds on my laptop, while @Maltysen's solution produced no solution in 20 minutes running time. 
But still a little bit too slow for the online compiler. 
### Explanation
```
u     ^4TZ   start with G = 0, for H in 0, ... 4^10-1:
                G = 
 +GhO4              G + (rand_int(4) + 1)
             result is printed implicitly 
```
[Answer]
# Java, 65
Since we have scores listed by language, why not throw Java into the mix? There's not much to golf here, just a simple loop, but I was able to squeeze a couple out of my initial attempt:
```
int f(){int i=1<<20,s=i;while(i-->0)s+=Math.random()*4;return s;}
```
[Answer]
# Matlab, 24
First submission ever! 
```
sum(randi([1,4],1,2^20))
```
I had hoped to make use of randi([1,4],1024), which gives a matrix of 1048576 elements, but then I needed a double sum, which takes more characters than this.
Regarding the running speed mentioned in the question, `timeit` tells me the runtime is about 0.031 seconds. So, pretty much instant.
[Answer]
## Haskell, 73 bytes
```
import System.Random
f=fmap sum.(sequence.replicate(2^20))$randomRIO(1,4)
```
Usage:
```
$ ghci sourcefile.hs
ghci> f
2622130
```
[Answer]
**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));}}
```
[Answer]
# 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.
[Answer]
# Mathematica, ~~30~~ 27 bytes
```
Tr[RandomInteger[3,2^20]+1]
```
Mathematica has quite long function names...
[Answer]
# 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.
[Answer]
# 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.
[Answer]
# Ruby, 32 bytes
```
(1..2**20).inject{|x|x-~rand(4)}
```
In a more readable form:
```
(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)`.
[Answer]
## 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();
  return total;
}
```
has a very small total operation count -- if [xorgens](https://maths-people.anu.edu.au/~brent/random.html) 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](https://en.wikipedia.org/wiki/Arithmetic_coding).
[Answer]
# Javascript, ~~55~~ ~~53~~ ~~50~~ ~~47~~ 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.
[Answer]
## [Clip 10](https://esolangs.org/wiki/Clip), 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.
[Answer]
# 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>
[Answer]
# 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)
[Answer]
## 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.
[Answer]
## PowerShell, 41 37 bytes
```
1..1mb|%{(get-random)%4+1}|measure -s
```
Took my machine 2 minutes 40 seconds
[Answer]
## 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](http://fishlanguage.com/playground/L8bSSCWp9R3Wo9pG8)'s the online interpreter.
[Answer]
# 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)
```
[Answer]
# Java (Java 8) - 52
```
int f(){return new Random().ints(1<<20,1,5).sum();}
```
]