Thursday 19 May 2016

Sum Of two arrays

There are 2 arrays of integers (from 0 to 9). You have to add those integers and keep it in 3rd array. There is one condition, if the sum is a 2 digit number, split that number into single digit and other condition is if any of the array integer is left then print that number

I/P:
int[] a = {1,2,3,4,5,6}
int[] b = {2,3,4,5,6,7,8}

o/p:

{3,5,7,9,1,1,1,3,8}

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ArraySum {

 public static int[] arraysSum(int arr1[], int arr2[]) {
  int empty[] = {};

  if (Objects.isNull(arr1) && Objects.isNull(arr2)) {
   return empty;
  } else if (Objects.isNull(arr1) || arr1.length == 0) {
   return arr2;
  } else if (Objects.isNull(arr2) || arr2.length == 0) {
   return arr1;
  }

  if (arr1.length > arr2.length)
   return getSum(arr1, arr2);

  return getSum(arr2, arr1);

 }

 private static int[] getSum(int arr1[], int arr2[]) {
  List<Integer> result = new ArrayList<>();

  for (int i = 0; i < arr2.length; i++) {
   int sum = arr1[i] + arr2[i];

   if (sum > 9) {
    String temp = new Integer(sum).toString();

    for (int j = 0; j < temp.length(); j++) {
     result.add(new Integer("" + temp.charAt(j)));
    }
    continue;
   }

   result.add(sum);
  }

  for (int j = arr2.length; j < arr1.length; j++) {
   result.add(arr1[j]);
  }

  return getArray(result);
 }

 private static int[] getArray(List<Integer> arr) {
  int result[] = new int[arr.size()];
  int i = 0;

  for (Integer data : arr) {
   result[i] = data;
   i++;
  }

  return result;
 }
}

import org.junit.Assert;
import org.junit.Test;

public class ArraySumTest {

 @Test
 public void testEmpty() {
  int arr1[] = {};
  int arr2[] = {};
  int arr3[] = { 1 };

  int expected1[] = {};
  int expected2[] = { 1 };

  Assert.assertArrayEquals(ArraySum.arraysSum(arr1, arr2), expected1);
  Assert.assertArrayEquals(ArraySum.arraysSum(arr1, arr3), expected2);
  Assert.assertArrayEquals(ArraySum.arraysSum(arr3, arr1), expected2);

 }

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

  int expected1[] = { 3, 5, 7, 9, 1, 1, 1, 3, 8 };

  Assert.assertArrayEquals(ArraySum.arraysSum(arr1, arr2), expected1);

 }

 @Test
 public void testNonEmpty2() {
  int arr1[] = { 1, 2, 3 };
  int arr2[] = { 9, 8, 7, 6, 5, 4 };

  int expected1[] = { 1, 0, 1, 0, 1, 0, 6, 5, 4 };

  Assert.assertArrayEquals(ArraySum.arraysSum(arr1, arr2), expected1);
  Assert.assertArrayEquals(ArraySum.arraysSum(arr2, arr1), expected1);

 }

}


No comments:

Post a Comment