Anonymous Kotlin function: Average of squares in a list
Write an anonymous Kotlin function to find the average of the squares of a list of numbers.
Pre-Knowledge (Before You Start!)
Before attempting this exercise, you should be familiar with the following concepts:
- Lists: A list is a collection of elements in Kotlin, and you can perform operations on these elements, such as mapping or summing.
- Anonymous Functions: You can define functions in Kotlin without names. These functions can be assigned to variables and called like any other function.
- Mapping: The map() function allows you to transform each element in a list. In this case, you'll square each element in the list.
- Calculating Average: To calculate the average, sum the values and divide by the number of elements in the list. In Kotlin, this can be done with the sum() function and division.
- Double Conversion: Make sure to convert the sum to a Double before dividing, as division of integers in Kotlin may result in truncation if not properly handled.
Hints (Try Before Looking at the Solution!)
Try to solve the problem with these hints:
- Hint 1: Create an anonymous function that takes a list of integers and returns a Double as the average of squares.
- Hint 2: Use map() to square each element in the list.
- Hint 3: Sum up the squared numbers using sum().
- Hint 4: Divide the total sum by the size of the list to find the average.
- Hint 5: Don't forget to handle the conversion to Double when calculating the average to avoid integer division issues.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics