Question

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)
Was it helpful?

Solution

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)) }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top