Generating permutations with scalacheck

I have generators like this:

val fooRepr = oneOf(a, b, c, d, e)
val foo = for (s <- choose(1, 5); c <- listOfN(s, fooRepr)) yield c.mkString("$")

This leads to duplication ... I can get two a, etc. I really want to create an arbitrary permutation accurate to 0 or 1, or each of a, b, c, d or e (with at least one something), in any order.

I thought there should be an easy way, but I'm struggling to find the hard way. :)

Edited: Ok, this seems to work:

val foo = for (s <- choose(1, 5);
               c <- permute(s, a, b, c, d, e)) yield c.mkString("$")

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

... borrowing heavily from Gen.pick.

Thanks for your help, -Eric

+3
source share
2 answers

Rex, , , , , , , scalacheck, , , . a, b, c .. .

, ; , , . , , github

. , ...

package powerset

import org.scalacheck._
import org.scalacheck.Gen._
import org.scalacheck.Gen
import scala.util.Random

object PowersetPermutations extends Properties("PowersetPermutations") {

  def a: Gen[String] = value("a")

  def b: Gen[String] = value("b")

  def c: Gen[String] = value("c")

  def d: Gen[String] = value("d")

  def e: Gen[String] = value("e")

  val foo = for (s <- choose(1, 5);
                 c <- permute(s, a, b, c, d, e)) yield c.mkString

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

  implicit def arbString: Arbitrary[String] = Arbitrary(foo)

  property("powerset") = Prop.forAll {
    a: String => println(a); true
  }
}

,

+2

, ( ) Edit: . N 2 ^ N, ( Scala, , ScalaCheck):

def powerSet[X](xs: List[X]) = {
  val xis = xs.zipWithIndex
  (for (j <- 1 until (1<<xs.length)) yield {
    for ((x,i) <- xis if ((j & (1<<i)) != 0)) yield x
  }).toList
}

, . , , , . , 1 (1<<(xs.length-1)) . ( Long, 33-64 , BitSet, .) , , .


Edit: , , : Stop. .takeWhile(_ != Stop). -! . ( , .)

+3

Source: https://habr.com/ru/post/1794491/


All Articles