Sunday 23 August 2015

First element added with the second, the second with the third

Write a recursive function where first element added with the second, the second with the third etc. (No change in last element),

For example,
If arr[] = {1,2,3,4,5} output is like {3,5,7,9,5}
import java.util.Objects;

public class ArraySum {

 public static void updateArray(int arr[]) {
  Objects.nonNull(arr);
  if (arr.length == 1)
   return;
  update(arr, 0);
 }

 private static void update(int arr[], int index) {
  if (index == arr.length - 1)
   return;

  arr[index] = arr[index] + arr[index + 1];
  update(arr, index + 1);
 }
}


Following is the junit test case for above program.

import static org.junit.Assert.assertTrue;

import java.util.Arrays;

import org.junit.Test;

public class ArraySumTest {

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

  ArraySum.updateArray(arr1);
  ArraySum.updateArray(arr2);

  assertTrue(Arrays.equals(arr1, expected1));
  assertTrue(Arrays.equals(arr2, expected2));
 }
}


No comments:

Post a Comment