scala – 就地调整ArrayBuffer的一部分
发布时间:2020-12-16 09:59:25 所属栏目:安全 来源:网络整理
导读:我需要对ArrayBuffer的一部分进行随机播放,最好是就地,因此不需要复制.例如,如果ArrayBuffer有10个元素,并且我想要移动元素3-7: // Unshuffled ArrayBuffer of ints numbered 0-90,1,2,3,4,5,6,7,8,9// Region I want to shuffle is between the pipe symbo
我需要对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,2 | 3,7 | 8,9 // Example of how it might look after shuffling 0,2 | 6,4 | 8,9 // Leaving us with a partially shuffled ArrayBuffer 0,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的事情.我假设我必须编写自己的方法,但这样做我想防止复制. 解决方法
我不完全确定为什么它必须到位 – 你可能想要考虑结束.但是,假设这是正确的事情,这可以做到:
import scala.collection.mutable.ArrayBuffer implicit def array2Shufflable[T](a: ArrayBuffer[T]) = new { def shufflePart(start: Int,end: Int) = { val seq = (start.max(0) until end.min(a.size - 1)).toSeq seq.zip(scala.util.Random.shuffle(seq)) foreach { t => val x = a(t._1) a.update(t._1,a(t._2)) a(t._2) = x } a } } 您可以像以下一样使用它: val a = ArrayBuffer(1,9) println(a) println(a.shufflePart(2,7)) 编辑:如果您愿意支付中间序列的额外费用,从算法来讲,这更合理: def shufflePart(start: Int,end: Int) = { val seq = (start.max(0) until end.min(a.size - 1)).toSeq seq.zip(scala.util.Random.shuffle(seq) map { i => a(i) }) foreach { t => a.update(t._1,t._2) } a } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |