Created
August 14, 2015 14:15
-
-
Save davepkennedy/064a23c2df8512987431 to your computer and use it in GitHub Desktop.
Shuffle some numbers using scala - possibly not the most efficient!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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