Skip to content

Instantly share code, notes, and snippets.

@dcbriccetti
Last active August 29, 2015 14:16
Show Gist options
  • Save dcbriccetti/b70a7ff65541d79c467d to your computer and use it in GitHub Desktop.
Save dcbriccetti/b70a7ff65541d79c467d to your computer and use it in GitHub Desktop.
Can you rewrite this to produce “combinations” for any nonzero value of “numDice”? (This is mostly academic curiosity.)
val combinations: Seq[Seq[Int]] = numDice match {
case 1 => for (a <- 1 to numSides) yield Seq(a)
case 2 => for (a <- 1 to numSides; b <- 1 to numSides) yield Seq(a, b)
case 3 => for (a <- 1 to numSides; b <- 1 to numSides; c <- 1 to numSides) yield Seq(a, b, c)
}
@mtm
Copy link

mtm commented Mar 14, 2015

Can't help with Scala (been away too long), but here's a way to do it in Clojure:

(defmacro die-rolls [num-dice num-sides]
  (let [sides (vec (range 1 (inc num-sides)))
        die-names (vec (repeatedly num-dice gensym))
        die-bindings (vec (mapcat #(list % sides) die-names))]
    `(for ~die-bindings
       ~die-names)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment