## Rolling the Groovy Dice

### January 6, 2013

Bit of a throw away post but it might save someone 5 minutes…  Nothing to do with Project Euler

I needed to have a quick way of rolling an arbitrary number of polyhedral dice including the ability to take a number of the highest from all those rolled.

I did this in Groovy by adding an overloaded `roll()` instance method to Integer along with a helper `isPolyhedralDie()` method (but only to catch me making some sort of basic typo in the calling code).

```Integer.metaClass.isPolyhedralDie() {
(delegate as Integer) in [ 3, 4, 6, 8, 10, 12, 20, 100 ]
}

Integer.metaClass.roll() {
delegate.roll(1)
}

Integer.metaClass.roll() { dice, best = dice ->;
assert delegate.isPolyhedralDie() && (best > 0) && (dice >= best)
def ( sides, rnd ) = [ delegate, new Random() ]
(1..dice).collect { rnd.nextInt(sides) + 1 }
.sort().reverse()[0..<best].sum()
}

// Generate 4x 3/4d6 character attribute sets

4.times {
def r = (1..6).collect { 6.roll(4,3) }
r.countBy { it }.sort { a, b -> b.key <=> a.key  }
.each { k, v -> print "\${v}x \$k, " }
println "Sum = \${r.sum()}"
}```

Usage:

```Integer#roll()                   // 6.roll() = roll 1d6
Integer#roll(noOfDice)           // 6.roll(3) = roll 3d6
Integer#roll(noOfDice, noOfBest) // 6.roll(4,3) = roll 4d6 take 3```