Chris Stewart
Chris Stewart

Reputation: 1679

How can I define a ScalaCheck generator that produces a subset of a sequence's elements?

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?

Upvotes: 2

Views: 811

Answers (2)

ryan
ryan

Reputation: 1084

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 }

Upvotes: 0

jub0bs
jub0bs

Reputation: 66244

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()

Upvotes: 4

Related Questions