Anonymous Kotlin function: Average of squares in a list
Kotlin Lambda: Exercise-14 with Solution
Write an anonymous Kotlin function to find the average of the squares of a list of numbers.
Sample Solution:
Kotlin Code:
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)
val averageSquares: (List<Int>) -> Double = fun(list: List<Int>): Double {
val sumOfSquares = list.map { it * it }.sum()
return sumOfSquares.toDouble() / list.size
}
val result = averageSquares(numbers)
println("List of numbers: $numbers")
println("Average of squares: $result")
}
Sample Output:
List of numbers: [1, 2, 3, 4, 5, 6] Average of squares: 15.166666666666666
Explanation:
In the above exercise -
- We define an anonymous function called averageSquares with the type (List<Int>) -> Double. It takes a list of integers (list) as its parameter and returns the average of the squares of the numbers in the list.
- Inside the averageSquares function, we use the map function to square each element in the list (list.map { it it }). Then, we calculate the sum of the squared numbers using the sum function (list.map { it it }.sum()).
- To find the average, we divide the sum of the squared numbers by the size of the list (sumOfSquares.toDouble() / list.size).
Kotlin Editor:
Previous: Concatenation of two strings.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/kotlin-exercises/lambda/kotlin-lambda-exercise-14.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics