Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating means of means of array of tuples in Scala

Tags:

scala

I'm writing a simple, short bit of code to demonstrate to a novice programmer how a series of random numbers converges in the mean. To do this, I've generated an array of tuples that store the size and mean of a randomly-sized and filled array. Here is the code I use to do that:

val random = new scala.util.Random()

def gen(random:scala.util.Random) = {
    val array = Array.fill(2 + random.nextInt(999)) { random.nextInt(100) }
    val sum = array.reduceLeft(_ + _)
    val mean = sum.toDouble / array.size
    (array.size, mean)
}

val array = Array.fill(10000) { gen(random) }

I then want to calculate the mean of the means of equal-sized arrays, put that in an array, and sort it by size of the original array. So, if I had an array of tuples: (2, 57), (2, 22), (2, 40), I would like a single entry of (2, (57+22+40)/3), and so on for each entry in the array.

I'm stuck how to do this in an elegant, idiomatic, and clear way in Scala. Would someone be able to help with that? And, if you have any constructive criticism for the above code, that would also help.

Thanks.

like image 409
Bill Lear Avatar asked Nov 19 '25 08:11

Bill Lear


1 Answers

assuming:

def mean(xs: Iterable[Double]) = xs.sum / xs.size

then:

array
  .groupBy(_._1)
  .mapValues(xs => mean(xs.map(_._2)))
  .toArray
  .sortBy(_._1)
like image 120
Seth Tisue Avatar answered Nov 21 '25 22:11

Seth Tisue



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!