How to calculate the median of an array?

后端 未结 14 1736
北海茫月
北海茫月 2020-12-05 06:10

I\'m trying to calculate the total, mean and median of an array thats populated by input received by a textfield. I\'ve managed to work out the total and the mean, I just ca

14条回答
  •  无人及你
    2020-12-05 06:50

    And nobody paying attention when list contains only one element (list.size == 1). All your answers will crash with index out of bound exception, because integer division returns zero (1 / 2 = 0). Correct answer (in Kotlin):

    MEDIAN("MEDIAN") {
    
            override fun calculate(values: List): BigDecimal? {
                if (values.size == 1) {
                    return values.first()
                }
                if (values.size > 1) {
                    val valuesSorted = values.sorted()
                    val mid = valuesSorted.size / 2
                    return if (valuesSorted.size % 2 != 0) {
                        valuesSorted[mid]
                    } else {
                        AVERAGE.calculate(listOf(valuesSorted[mid - 1], valuesSorted[mid]))
                    }
                }
                return null
            }
        },
    

提交回复
热议问题