I wrote this code to calculate median range but I want to give every column and row a specific name like:
Columns A B C D
Rows 1 2 3
I have to calculate the median of a range like in excel A2:C3 so the program can calculate A2 A3 B2 B3 C2 C3 and if it's B3:D3 I want it to calculate B3 C3 D3.
This is my code:
fun med(list: List<Double>) = list.sorted().let {
(it[it.size / 2] + it[(it.size - 1) / 2]) / 2
}
fun main(args: Array<String>) {
med(listOf(1.5, 2.67, 3.0, 1.4)).let { println(it) }
med(listOf(5.2, 7.1, -4.8, 0.0)).let { println(it) }
med(listOf(1.4, 6.0, 2.5, -1.9)).let { println(it) }
}
You should check the length of a list and return the middle element if the length is odd:
fun med(list: List<Double>) = list.sorted().let {
if (it.size % 2 == 0)
(it[it.size / 2] + it[(it.size - 1) / 2]) / 2
else
it[it.size / 2]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With