我需要对 ArrayBuffer 的一部分进行洗牌,最好是就地洗牌,因此不需要副本。例如,如果一个 ArrayBuffer 有 10 个元素,并且我想打乱第 3-7 个元素:
// Unshuffled ArrayBuffer of ints numbered 0-9
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
// Region I want to shuffle is between the pipe symbols (3-7)
0, 1, 2 | 3, 4, 5, 6, 7 | 8, 9
// Example of how it might look after shuffling
0, 1, 2 | 6, 3, 5, 7, 4 | 8, 9
// Leaving us with a partially shuffled ArrayBuffer
0, 1, 2, 6, 3, 5, 7, 4, 8, 9
我已经编写了如下所示的内容,但它需要复制并迭代循环几次。似乎应该有一种更有效的方法来做到这一点。
def shufflePart(startIndex: Int, endIndex: Int) {
val part: ArrayBuffer[Int] = ArrayBuffer[Int]()
for (i <- startIndex to endIndex ) {
part += this.children(i)
}
// Shuffle the part of the array we copied
val shuffled = this.random.shuffle(part)
var count: Int = 0
// Overwrite the part of the array we chose with the shuffled version of it
for (i <- startIndex to endIndex ) {
this.children(i) = shuffled(count)
count += 1
}
}
我找不到关于使用 Google 部分改组 ArrayBuffer 的信息。我假设我必须编写自己的方法,但这样做我想防止复制。