How can I generate a list of n unique elements selected from a set?

How to generate a list of n unique values ​​( Gen[List[T]]

) from a set of values ​​(not generators) using ScalaCheck? This post uses Gen[T]*

a set of values ​​instead and I cannot rewrite it to make it work.

EDIT

As requested by @Jubobs, I now shamefully show what I have tried so far by showing my full newbie status when using ScalaCheck :-)

I just tried to replace the gs: Gen[T]

duplicate parameter with Set

what @Eric wrote as the solution here :

def permute[T](n: Int, gs: Set[T]): Gen[Seq[T]] = {
    val perm = Random.shuffle(gs.toList)
    for {
        is <- Gen.pick(n, 1 until gs.size)
        xs <- Gen.sequence[List[T], T](is.toList.map(perm(_)))
    } yield xs
}

      

but is.toList.map(perm(_))

got an underlined red and IntelliJ IDEA told me that "you should first read the ScalaCheck API before a blind (albeit intuitive) probe and error", or maybe "Type mismatch: expected: Traversable [Gen [T] ], the actual list [T] "I do not remember.

I have also tried several other ways, most of which I find funny (and therefore not worthy of posting) in retrospect, the most naive of which is @Eric's use of an otherwise useful and neat as-is solution:

val g = for (i1 <- Gen.choose(0, myList1.length - 1); 
  i2 <- Gen.choose(0, myList2.length - 1)) 
  yield new MyObject(myList1(i1), myList2(i2))
val pleaseNoDuplicatesPlease = permute(4, g, g, g, g, g)

      

After some testing, I saw that pleaseNoDuplicatesPlease

it actually contains duplicates, after which I weighed my ability to read through the ScalaCheck API and understand much more than I do now (which will inevitably and gradually come), or posting my question to StackOverflow (after careful searching, there are whether similar questions).

+3


source to share


1 answer


Gen.pick

is right up your alley:



scala> import org.scalacheck.Gen
import org.scalacheck.Gen

scala> val set = Set(1,2,3,4,5,6)
set: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 3, 4)

scala> val myGen = Gen.pick(5, set).map { _.toList }
myGen: org.scalacheck.Gen[scala.collection.immutable.List[Int]] = org.scalacheck.Gen$$anon$3@78693eee

scala> myGen.sample
res0: Option[scala.collection.immutable.List[Int]] = Some(List(5, 6, 2, 3, 4))

scala> myGen.sample
res1: Option[scala.collection.immutable.List[Int] = Some(List(1, 6, 2, 3, 4))

      

+4


source







All Articles