I need to randomly sample a subset of n elements from a list in Scala, and I was wondering if there was a convenient way to do so without recourse to manually checking that each of the n elements are unique. At the moment I have something like this:
import util.Random
def sample(itms:List[A], sampleSize:Int) {
var numbersSeen = Set[Int]()
var sampled = List[A]()
val itmLen = itms.size()
var sampleIdex = Random.nextInt(itmLen)
while(sampled < sampleSize) {
if(numbersSeen.contains(sampleIdex)){
sampleIdex = Random.nextInt(itmLen)
} else {
numbersSeen.add(sampleIdex)
sampled.add(itms(sampleIdex))
}
}
sampled
}
I was hoping there was something more elegant that can be done to either generate a non-repeating random list of integers in a range or to randomly sample n elements from a list.