生成一个集合,新添加的元素取决于已添加的元素

时间:2018-06-05 12:32:27

标签: scala

我想从输入集合observations创建一组随机选择的索引:

case class Observation(id: Long, metric1: Double)

val observations: Seq[Observation]

val NumSamples = 100
val indices = // A set of randomly selected indices of the observations
              // WITHOUT replacement

复杂的是,为了避免在选择新索引时替换现有索引(通过myRandom.nextInt(observations.length),我们需要访问到之前的索引 - 这在此期间是不可能的。初始生成序列。

此处显示了我正在寻找的内容

最喜欢的(但我怀疑它可以做到。)

val sampledIndices: Seq[Int] = for (randInd <- 0 until NSamples) yield {
    // some random non-repeated index in [0..length(observations)]
}

但是以下是第二选择

val randomIndices = mutable.ArrayBuffer[Int]()
for (randInd <- 0 until NSamples) {
   randomIndices ++= // some random non-repeated index in
}

要避免什么:多个var s ..这是我到目前为止所遇到的。

2 个答案:

答案 0 :(得分:2)

我认为这可以做你想要的事情

val sampledIndices: Seq[Int] = scala.util.Random.shuffle((0 until observations.size))

答案 1 :(得分:1)

另一种选择是使用展开功能,通过创建值和状态来创建流,以在每个步骤中获取下一个值

def unfold[A,S](z: S)(implicit f: S => Option[(A,S)]): Stream[A] = {
  f(z) match{
    case None => Stream[A]()
    case Some((value, state)) => value#::unfold(state)
  }
}

然后创建你的列表:

unfold(Random)((a => Some(a.nextInt, a))).take(NSamples).toList