Skip to content

Instantly share code, notes, and snippets.

@davepkennedy
Created August 14, 2015 14:15
Show Gist options
  • Save davepkennedy/064a23c2df8512987431 to your computer and use it in GitHub Desktop.
Save davepkennedy/064a23c2df8512987431 to your computer and use it in GitHub Desktop.
Shuffle some numbers using scala - possibly not the most efficient!
import scala.annotation.tailrec
import scala.util.Random
def shuffle (values: List[Int]): List[Int] = {
val r = new Random()
@tailrec
def shuffle0 (values: List[Int], accum: List[Int] = List.empty): List[Int] = values match {
case List(x) => x :: accum
case h :: t =>
val idx = r.nextInt(t.length)
shuffle0 (t.updated(idx, h), t(idx) :: accum)
}
shuffle0 (values)
}
shuffle (List (1,2,3,4,5,6,7,8,9))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment