The challenge
Write function avg which calculates average of numbers in given list.
The solution in Java code
Option 1 (working through the problem):
public class Solution {
public static double find_average(int[] array){
double sum = 0;
for(int i=0; i<array.length; i++) {
sum+=array[i];
}
return sum/array.length;
}
}
Option 2 (using streams
):
import java.util.Arrays;
public class Solution {
public static double find_average(int[] array){
return Arrays.stream(array).average().orElse(0);
}
}
Option 3 (using an IntStream
):
import java.util.stream.IntStream;
public class Solution {
public static double find_average(int[] array){
return IntStream.of(array).average().getAsDouble();
}
}
Option 4 (an alternate IntStream
approach):
import java.util.stream.IntStream;
public class Solution {
public static double find_average(int[] array){
return IntStream.of(array).sum() / (double) array.length;
}
}
Test cases to validate our solution
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
private static final double DELTA = 1e-15;
@Test
public void testSomething() {
assertEquals(1, Solution.find_average(new int[]{1,1,1}), DELTA);
assertEquals(2, Solution.find_average(new int[]{1, 2, 3}), DELTA);
assertEquals(2.5, Solution.find_average(new int[]{1, 2, 3, 4}), DELTA);
System.out.println("Running 20 random tests...");
for(int i=0; i<20; i++){
int[] arr = randArray();
assertEquals(solution(arr), Solution.find_average(arr), DELTA);
}
}
private static int[] randArray(){
int size = (int)Math.floor(Math.random()*5 + 2);
int[] arr = new int[size];
for(int i=0; i<size; i++){
arr[i] = (int)Math.floor(Math.random()*20 + 1);
}
return arr;
}
private static double solution(int[] arr){
int sum = 0;
for(int i=0; i<arr.length; i++){
sum += arr[i];
}
return (sum + 0.0) / arr.length;
}
}