How can I pick a subset of the elements of a sequence?
For instance, if I had the sequence Seq(1,2,3,4,5), I'd like each call to my generator to produce something like
Seq(1,4) or
Seq(1,2,3,5) or
Seq() How can I define such a generator?
org.scalacheck.Gen.someOf is a generator that picks a random number of elements from an iterable:
scala> import org.scalacheck.Gen import org.scalacheck.Gen scala> val baseSeq = Seq(1, 2, 3, 4, 5) baseSeq: Seq[Int] = List(1, 2, 3, 4, 5) scala> val myGen = Gen.someOf(baseSeq).map(_.toSeq) myGen: org.scalacheck.Gen[Seq[Int]] = org.scalacheck.Gen$$anon$6@ff6a218 scala> myGen.sample.head res0: Seq[Int] = List(3, 4, 5) scala> myGen.sample.head res1: Seq[Int] = List(1, 2, 3, 4) scala> myGen.sample.head res2: Seq[Int] = List() This depends on the probability for each element to show up in your result. For example, for any element to show up with 50% chance, you can use the following. Hope this helps.
import scala.util.Random val s = Seq(1,2,3,4,5) s filter { i => Random.nextInt(2) == 1 } Gen[Seq[Int]].
Seqyou pick from have unique elements?