简体   繁体   中英

resampling in scala, the functional way

I have an array of samples, D, that I would like to uniformly re-sample with replacement to construct a new array. A procedural solutions is very straightforward, but I wonder if anyone has some ideas on how to do it "the functional way" ? (I've only just picked up Scala and functional programming)

A functional implementation to demonstrate what I mean:

val D = Array(0,1,2,3,4)  

val R = new Random();                           
var ResampledD = Array[Int]();           
var i = 0;                                      
while (i < D.length) {
    ResampledD = ResampledD :+ D(R.nextInt(D.length));
    i = i + 1;
} 
ResampledD
> res0: Array[Array[Int]] = Array(2, 2, 1, 3, 2)

The Array companion object has some methods to build new arrays, and the one you need is fill :

val ResampledD = Array.fill(D.length)(D(util.Random.nextInt(D.length)))

or use map

val ResampledD = D map { x => D(util.Random.nextInt(D.length)) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM