Sunday 23 August 2015

Recursive function to find number of occurrence of element in given array


Write a recursive program that finds the number of times that x occurs in the list.
import java.util.Objects;

public class FindOccurrences {

 public static int findOccurrences(int arr[], int x) {
  Objects.nonNull(arr);

  return count(arr, 0, x);
 }

 private static int count(int arr[], int index, int element) {
  if (index == arr.length)
   return 0;

  if (arr[index] == element)
   return 1 + count(arr, index + 1, element);

  return count(arr, index + 1, element);
 }
}


Following is the junit test case for above program.

import static org.junit.Assert.assertEquals;

import org.junit.Test;

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

  assertEquals(FindOccurrences.findOccurrences(arr1, 1), 1);
  assertEquals(FindOccurrences.findOccurrences(arr1, 2), 2);
  assertEquals(FindOccurrences.findOccurrences(arr1, 3), 3);
  assertEquals(FindOccurrences.findOccurrences(arr1, 4), 4);
 }
}


No comments:

Post a Comment