20
\$\begingroup\$

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

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

\$\endgroup\$
  • \$\begingroup\$ Wait, do I have to give the sum of the dice roll or just all the rolls in a list? \$\endgroup\$ – Maltysen Apr 30 '15 at 1:58
  • 5
    \$\begingroup\$ 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. \$\endgroup\$ – BrainSteel Apr 30 '15 at 2:05
  • 2
    \$\begingroup\$ This problem can be done too quickly to be a good time trial. \$\endgroup\$ – isaacg Apr 30 '15 at 2:57
  • 12
    \$\begingroup\$ You could try your hand at making a stack snippet leaderboard to avoid having to manually keep the list of submissions up to date. \$\endgroup\$ – Alex A. Apr 30 '15 at 14:32
  • 1
    \$\begingroup\$ I absolutely love this title. \$\endgroup\$ – ASCIIThenANSI Apr 30 '15 at 22:19

43 Answers 43

10
\$\begingroup\$

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
\$\endgroup\$
  • 4
    \$\begingroup\$ 8 bytes are possible. 2^20 = 4^10 \$\endgroup\$ – Jakube Apr 30 '15 at 9:34
  • \$\begingroup\$ @Jakube thanks for the tip :) \$\endgroup\$ – Maltysen Apr 30 '15 at 16:35
  • \$\begingroup\$ This finishes immediately for me. \$\endgroup\$ – Carcigenicate May 2 '15 at 0:16
  • \$\begingroup\$ @Carcigenicate are you talking about the link I gave? That's the modified one, only sums 1024d4. \$\endgroup\$ – Maltysen May 2 '15 at 0:35
  • \$\begingroup\$ @Maltysen Whoops, sorry. Ya, that's it. \$\endgroup\$ – Carcigenicate May 2 '15 at 0:36
9
\$\begingroup\$

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";
\$\endgroup\$
  • \$\begingroup\$ It was a little hard to get a timer hooked up, but I eventually got it working. \$\endgroup\$ – SuperJedi224 Apr 30 '15 at 2:35
  • 2
    \$\begingroup\$ Since we dont care about warnings ... $s+=int rand(5)for(1..2**20);print$s \$\endgroup\$ – Thaylon Apr 30 '15 at 14:11
  • 3
    \$\begingroup\$ int(rand(5)) returns range 0 to 4 while d4 should be 1 to 4. \$\endgroup\$ – nutki Apr 30 '15 at 19:19
  • \$\begingroup\$ @nutki OK, thanks. I've edited that in now. \$\endgroup\$ – ASCIIThenANSI Apr 30 '15 at 20:05
  • \$\begingroup\$ $s+=int rand(4)+1for(1..2**20);print$s Removing the parenthesis for int also works for me, to save a stroke. \$\endgroup\$ – Caek May 1 '15 at 5:03
7
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ One and 5??? A d4 can give 1, 2, 3 or 4. You can't get 5. \$\endgroup\$ – Loren Pechtel Apr 30 '15 at 3:59
  • \$\begingroup\$ @LorenPechtel: Sorry, my bad. Thanks for pointing that out. It's fixed now. I have tired brain. \$\endgroup\$ – Alex A. Apr 30 '15 at 4:02
  • \$\begingroup\$ Save a byte: +/?4⍴⍨2*20 \$\endgroup\$ – marinus Apr 30 '15 at 9:35
  • \$\begingroup\$ Small improvement: use +/?4⍴⍨2*20 instead. \$\endgroup\$ – FUZxxl Apr 30 '15 at 11:50
  • 1
    \$\begingroup\$ Incidtenally, this answer is not golfed in any way: It would be written exactly the same way in production APL code. \$\endgroup\$ – FUZxxl Jul 11 '15 at 21:13
7
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ +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. \$\endgroup\$ – ASCIIThenANSI Apr 30 '15 at 14:15
  • \$\begingroup\$ I presume there's a function for sampling a normal distribution rather than a uniform one? Should be much quicker. \$\endgroup\$ – Ben Voigt Apr 30 '15 at 18:25
  • \$\begingroup\$ @BenVoigt: Since this is meant to simulate the rolling of dice, a normal distribution is not appropriate; it would have to be uniform. \$\endgroup\$ – Alex A. Apr 30 '15 at 19:47
  • 2
    \$\begingroup\$ @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". \$\endgroup\$ – Ben Voigt Apr 30 '15 at 20:34
  • 1
    \$\begingroup\$ @M.I.Wright, I thought it was just for communication. At least the one I've got uses AAA batteries. \$\endgroup\$ – Arturo Torres Sánchez Apr 30 '15 at 21:35
7
\$\begingroup\$

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 
\$\endgroup\$
  • \$\begingroup\$ You can save a couple bytes by using sample() in place of runif(), i.e. sum(sample(4,2^20,r=T)). \$\endgroup\$ – Alex A. Apr 30 '15 at 4:09
  • \$\begingroup\$ Just did some benchmarking on my computer and sample() is actually faster too! \$\endgroup\$ – Alex A. Apr 30 '15 at 4:26
  • \$\begingroup\$ @AlexA. Thanks will test and change when I get close to a computer \$\endgroup\$ – MickyT Apr 30 '15 at 6:05
  • \$\begingroup\$ not to necro this or anything but you don't need r=T, just T is fine for replacement. \$\endgroup\$ – Giuseppe Jun 12 '17 at 21:12
  • 1
    \$\begingroup\$ @Giuseppe, thanks .. this really was an old one \$\endgroup\$ – MickyT Jun 12 '17 at 21:33
6
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – SuperJedi224 Apr 30 '15 at 15:47
  • \$\begingroup\$ @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. \$\endgroup\$ – Optimizer Apr 30 '15 at 15:48
  • 3
    \$\begingroup\$ 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+}* \$\endgroup\$ – DocMax Apr 30 '15 at 19:34
  • \$\begingroup\$ @DocMax You are right. Thanks! \$\endgroup\$ – Optimizer Apr 30 '15 at 19:36
  • \$\begingroup\$ +1; I was going to post this exact answer (except with 4A# instead of YK#), but you beat me to it. :) \$\endgroup\$ – Ilmari Karonen Apr 30 '15 at 21:00
6
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Doesn't work in chrome. About to test in FF. \$\endgroup\$ – SuperJedi224 Apr 30 '15 at 21:31
  • \$\begingroup\$ Of course. Chrome is ES5 \$\endgroup\$ – edc65 Apr 30 '15 at 21:31
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ – SuperJedi224 Apr 30 '15 at 21:32
5
\$\begingroup\$

Perl, 29

Generates a table of the required length.

print~~map{0..rand 4}1..2**20
\$\endgroup\$
  • \$\begingroup\$ I'm getting a syntax error on this one. \$\endgroup\$ – SuperJedi224 Apr 30 '15 at 22:03
  • \$\begingroup\$ 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). \$\endgroup\$ – Mark Apr 30 '15 at 23:31
  • \$\begingroup\$ ~~ 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 \$\endgroup\$ – nutki May 1 '15 at 10:50
  • \$\begingroup\$ Yep, it works on IDEone. I'll give it to you. \$\endgroup\$ – SuperJedi224 May 1 '15 at 13:49
5
\$\begingroup\$

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

\$\endgroup\$
4
\$\begingroup\$

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 
\$\endgroup\$
  • \$\begingroup\$ Will test this this afternoon. \$\endgroup\$ – SuperJedi224 Apr 30 '15 at 13:51
4
\$\begingroup\$

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;}
\$\endgroup\$
  • \$\begingroup\$ Will test this this afternoon. \$\endgroup\$ – SuperJedi224 Apr 30 '15 at 13:51
  • \$\begingroup\$ No problem. It takes around 80ms on this (slow) PC, but I don't know what you're using to time. \$\endgroup\$ – Geobits Apr 30 '15 at 13:55
  • \$\begingroup\$ I do not believe your program is a correct model. It can and does in my testing add 0 on some rolls. As I understand it most d4's are 1,2,3,4 (no 0 possible). \$\endgroup\$ – user39526 May 1 '15 at 19:33
  • 4
    \$\begingroup\$ @user39526 s (the total sum) starts at 1<<20 (the number of rolls). This is equivalent to adding one to each roll. When the randomizer throws 0, it's rolled a 1, etc. \$\endgroup\$ – Geobits May 1 '15 at 19:42
  • \$\begingroup\$ You should upgrade to Java 8 !codegolf.stackexchange.com/a/52919/7021 \$\endgroup\$ – RobAu Jul 10 '15 at 12:35
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ I'm getting 0.04 to 0.05 seconds via octave online. \$\endgroup\$ – SuperJedi224 Apr 30 '15 at 13:48
4
\$\begingroup\$

Haskell, 73 bytes

import System.Random
f=fmap sum.(sequence.replicate(2^20))$randomRIO(1,4)

Usage:

$ ghci sourcefile.hs
ghci> f
2622130
\$\endgroup\$
4
\$\begingroup\$

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));}}
\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – edc65 May 1 '15 at 22:04
  • \$\begingroup\$ @edc65 Thanks for catching those errors. I have updated the answer. \$\endgroup\$ – Andrew May 1 '15 at 22:08
  • 1
    \$\begingroup\$ 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? \$\endgroup\$ – LegionMammal978 May 2 '15 at 1:28
  • \$\begingroup\$ @LegionMammal978 if you create a new Random again and again, the result is mostly non-random \$\endgroup\$ – edc65 May 3 '15 at 20:24
  • \$\begingroup\$ @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. \$\endgroup\$ – Andrew May 3 '15 at 20:34
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ You can remove the ; after echo$v \$\endgroup\$ – Martijn May 1 '15 at 13:24
  • \$\begingroup\$ @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. \$\endgroup\$ – Ismael Miguel May 1 '15 at 18:20
4
\$\begingroup\$

Mathematica, 30 27 bytes

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

Mathematica has quite long function names...

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Why would you need to add srand(time(0))? (Sorry, I don't use C.) \$\endgroup\$ – ASCIIThenANSI Apr 30 '15 at 16:27
  • \$\begingroup\$ @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. \$\endgroup\$ – Functino Apr 30 '15 at 16:31
  • \$\begingroup\$ If you initialize a=b=1<<20 then you can skip 1+, this saves 4 bytes. \$\endgroup\$ – nutki Apr 30 '15 at 19:23
  • \$\begingroup\$ Also, int before main is not required. \$\endgroup\$ – nutki Apr 30 '15 at 19:45
  • \$\begingroup\$ Hint to anybody doing t=0, then t=t (...) +1 for 1048576 times: think again! (see my answer, eventually) \$\endgroup\$ – edc65 Apr 30 '15 at 20:38
3
\$\begingroup\$

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.

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

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

\$\endgroup\$
  • 1
    \$\begingroup\$ Could you explain how it works? \$\endgroup\$ – ASCIIThenANSI Apr 30 '15 at 16:41
  • \$\begingroup\$ 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. \$\endgroup\$ – SuperJedi224 May 1 '15 at 13:39
  • \$\begingroup\$ Okay, I found one that works. \$\endgroup\$ – SuperJedi224 May 1 '15 at 13:45
  • \$\begingroup\$ Bit twiddling hack: x-~rand(4) is equivalent to x+rand(4)+1. \$\endgroup\$ – histocrat May 2 '15 at 18:53
  • \$\begingroup\$ Also, you can replace 2**20 with 4e10. \$\endgroup\$ – histocrat May 2 '15 at 18:53
3
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Note that this answer is completely different from the one originally commented on by SuperJedi224 and @Andrew \$\endgroup\$ – Ralph Marshall May 2 '15 at 19:15
  • \$\begingroup\$ 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. \$\endgroup\$ – SuperJedi224 May 2 '15 at 19:49
  • \$\begingroup\$ 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. \$\endgroup\$ – Ralph Marshall May 3 '15 at 1:31
  • \$\begingroup\$ 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. \$\endgroup\$ – Ismael Miguel May 3 '15 at 17:45
  • \$\begingroup\$ You can golf it down to this: for(a=i=1<<20;i--;)a+=(Math.random()*4)|0, that's only 41 bytes \$\endgroup\$ – SuperJedi224 May 30 '15 at 18:18
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – SuperJedi224 Apr 30 '15 at 14:12
2
\$\begingroup\$

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)

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

PowerShell, 41 37 bytes

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

Took my machine 2 minutes 40 seconds

\$\endgroup\$
2
\$\begingroup\$

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.

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

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)
\$\endgroup\$
2
\$\begingroup\$

Java (Java 8) - 52

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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