如何生成从集合中选取的n个唯一元素的列表? [英] How can I generate a list of n unique elements picked from a set?
问题描述
如何使用ScalaCheck从一组值(而不是生成器)中生成n个唯一值(Gen[List[T]]
)的列表? 这篇文章使用Gen[T]*
而不是一组值,我似乎无法对其进行重写以使其正常工作.
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]*
instead of a set of values, and I can't seem to rewrite it to make it work.
编辑
在@Jubobs的请求下,我现在可耻地展示了我到目前为止已经尝试过的内容,以揭示我在使用ScalaCheck时的新手状态:-)
At @Jubobs' request I now shamefully display what I have tried so far, revealing my utter novice status at using ScalaCheck :-)
我只是尝试将@cric写为解决方案的内容中的gs: Gen[T]
重复参数替换为Set
I simply tried to replace gs: Gen[T]
repeated parameter to a Set
in what @Eric wrote as a 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
}
但是is.toList.map(perm(_))
用红色下划线标记,IntelliJ IDEA告诉我您应该在盲目(尽管直观)试验和错误之前先阅读ScalaCheck API" ,或者也许是" Type不匹配,预期:Traversable [Gen [T]],实际列表[T]",我不记得了.
but is.toList.map(perm(_))
got underlined with red, with IntelliJ IDEA telling me that "You should read ScalaCheck API first before blind (although intuitive) trial and error", or maybe "Type mismatch, expected: Traversable[Gen[T]], actual List[T]", I can't remember.
我还尝试了其他几种方法,事后看来,我发现其中大多数方法都是荒谬的(因此不值得发布),其中最幼稚的是按原样使用@Eric的解决方案(否则有用而整洁):>
I also tried several other ways, most of which I find ridiculous (and thus not worthy of posting) in hindsight, with the most naive being the using of @Eric's (otherwise useful and neat) solution as-is:
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)
经过一些测试,我发现pleaseNoDuplicatesPlease
实际上包含重复项,这时我权衡了我必须阅读ScalaCheck API并比现在更多地理解的更多选择(这不可避免,并会逐渐出现) ,或将我的问题发布到StackOverflow(在仔细搜索是否存在类似问题之后).
After some testing I saw that pleaseNoDuplicatesPlease
in fact contained duplicates, at which point I weighed my options of having to read through ScalaCheck API and understand a whole lot more than I do now (which will inevitably, and gradually come), or posting my question at StackOverflow (after carefully searching whether similar questions exist).
推荐答案
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))
这篇关于如何生成从集合中选取的n个唯一元素的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!