Sunday 23 August 2015

Find mean of array recursively

The mean is the average of the numbers. Add up all the numbers, then divide by how many numbers there are.
import java.util.Objects;

public class MeanCalc {

 public static double getMean(int arr[]) {
  Objects.nonNull(arr);
  if (arr.length == 0)
   throw new IllegalArgumentException("Array is empty");

  return sum(arr, 0) / arr.length;
 }

 private static double sum(int[] arr, int index) {
  if (index == arr.length - 1)
   return arr[index];
  return arr[index] + sum(arr, ++index);
 }
}


Following is the junit test case for above program.
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class MeanCalcTest {

 @Test
 public void test1() {
  int arr1[] = { 1, 2, 3, 4 };
  int arr2[] = { 5 };

  assertTrue(MeanCalc.getMean(arr1) == 2.5);
  assertTrue(MeanCalc.getMean(arr2) == 5);
 }
}


No comments:

Post a Comment