https://kotlinlang.org logo
#codereview
Title
# codereview
b

Brian Carbone

10/28/2019, 2:53 PM
Copy code
val Array<Coordinate>.centroid
    get() = fold(mutableMapOf<Double, Double>()) { acc, coord -> acc.also { it[coord.x] = coord.y } }.run {
        Coordinate(keys.average(), values.average())
    }
Is there a better way to get the average coordinate from an array of coordinates? (Coordinate is a simple data class holding two doubles, x and y)
d

Dominaezzz

10/28/2019, 3:13 PM
To just simplify....
Copy code
val Array<Coordinate>.centroid
    get() = associateBy({ it.x }, { it.y }).run {
        Coordinate(keys.average(), values.average())
    }
b

Brian Carbone

10/28/2019, 3:15 PM
oh lol
thanks
d

Dominaezzz

10/28/2019, 3:16 PM
Better would be something like this.
Copy code
val Array<Coordinate>.centroid
    get() = Coordinate(map { it.x }.average(), map { it.y }.average())
Sadly there's no
averageBy
.
3
b

Brian Carbone

10/28/2019, 3:17 PM
oh that's also good
yeah I'm not sure how I avoided any of the simpler options but thanks again
4 Views