[Programmers / JAVA] Level 1 Calculating the Average (12944)
[Programmers / JAVA] Level 1 Calculating the Average (12944)
Complete the function solution that returns the average value of the array arr, which holds integers.
@RWBwritten at 2021-12-18 12:43:34
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
Complete the function solution that returns the average value of the array arr, which holds integers.
- arr is an array with a length between 1 and 100, inclusive.
- The elements of arr are integers between -10,000 and 10,000, inclusive.
| arr | return |
|---|---|
| { 1, 2, 3, 4 } | 2.5 |
| { 5, 5 } | 5 |
We need to calculate and return the average of the elements in array arr. Using Stream, we can easily obtain it without a loop.
Arrays.stream(arr).sum() can be used to compute the total sum of the array elements in one go.
JAVA
import java.util.Arrays; /** * Calculating the Average class * * @author RWB * @since 2021.12.13 Mon 21:49:40 */ class Solution { /** * Method that returns the answer * * @param arr: [int[]] integer array * * @return [double] answer */ public double solution(int[] arr) { return (double) Arrays.stream(arr).sum() / arr.length; } }
# Programmers# Algorithm# JAVA# Level 1
