2

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?

3
  • Does the Seq you pick from have unique elements? Commented Aug 12, 2016 at 16:45
  • Yes that is what I had in mind Commented Aug 12, 2016 at 16:48
  • Yes, it is not a strict (proper) subset Commented Aug 12, 2016 at 16:53

2 Answers 2

4

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() 
Sign up to request clarification or add additional context in comments.

Comments

0

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 } 

1 Comment

This is in the context of ScalaCheck so OP is looking for return type like Gen[Seq[Int]].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.