Last active
August 1, 2017 06:24
-
-
Save thsutton/f3aeb1af9928bec10499f6167d95b877 to your computer and use it in GitHub Desktop.
Some generators for choices, permutations, shuffling, etc.
This file contains 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 scalaprops._ | |
/** Generate a permutation of the given values. | |
* | |
* > permute("ABC").sample | |
* Vector(A,C,B) | |
* > permute("ABC").sample | |
* Vector(B,A,C) | |
*/ | |
def permute[A](values: IndexedSeq[A]): Gen[IndexedSeq[A]] = | |
for { | |
selections <- permutation(values.size) | |
} yield selections.toIndexedSeq.map(n => values(n)) | |
/** Generate a permutation of `size` elements. | |
* | |
* > permutation(3).sample | |
* Seq(1,2,3) | |
* > permutation(3).sample | |
* Seq(3,1,2) | |
*/ | |
def permutation(size: Int): Gen[Seq[Int]] = | |
selection(size, size) | |
/** Generate a selection of `choose` items from `available` options. | |
* | |
* > selection(5, 3).sample | |
* Seq(4,1,2) | |
* > selection(5, 2).sample | |
* Seq(1,4) | |
*/ | |
def selection(available: Int, choose: Int): Gen[Seq[Int]] = | |
for { | |
keys <- Gen.sequenceNList(available, Gen[Double]).map(_.toSeq) | |
selections = keys.zip(1 to available).sortBy(_._1).map(_._2) | |
} yield selections.take(choose) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment