Skip to content

Commit 31ec4cf

Browse files
committed
Merge pull request kennyledet#89 from lichtsprung/master
added fisher-yates in scala
2 parents ab19ce9 + 637c8d1 commit 31ec4cf

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import scala.util.Random
2+
3+
object fisheryates_shuffle {
4+
5+
def shuffle_inplace[T](values: Array[T]): Unit = {
6+
for (i values.size to 1) swap(i, Random.nextInt(i), values)
7+
}
8+
9+
def shuffle[T](values: Array[T]): Array[T] = {
10+
val shuffled = values.clone()
11+
for (i shuffled.size to 1) swap(i, Random.nextInt(i), shuffled)
12+
shuffled
13+
}
14+
15+
private def swap[T](x: Int, y: Int, s: Array[T]): Unit = {
16+
val tmp = s(x)
17+
s(x) = s(y)
18+
s(y) = tmp
19+
}
20+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import org.scalatest.{ Matchers, FlatSpec }
2+
import fisheryates_shuffle._
3+
4+
class fisheryates_shuffle_test extends FlatSpec with Matchers {
5+
6+
"Fisher-Yates Shuffle (inplace)" should "shuffles the values of the array inplace" in {
7+
val values = Array(1, 2, 3, 4, 5)
8+
shuffle_inplace(values)
9+
values should contain allOf (1, 2, 3, 4, 5)
10+
values should contain inOrder (1, 2, 3, 4, 5)
11+
values.permutations.find(_.deep == values.deep).nonEmpty shouldBe true
12+
}
13+
14+
"Fisher-Yates Shuffle" should "return a random permutation of the source array" in {
15+
val values = Array(1, 2, 3, 4, 5)
16+
val shuffled = shuffle(values)
17+
shuffled should contain allOf (1, 2, 3, 4, 5)
18+
values should contain inOrder (1, 2, 3, 4, 5)
19+
values.permutations.find(_.deep == shuffled.deep).nonEmpty shouldBe true
20+
}
21+
}

0 commit comments

Comments
 (0)