The challenge

In this simple exercise, you will create a program that will take two lists of integers, a and b. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids a and b. You must find the difference of the cuboids’ volumes regardless of which is bigger.

For example, if the parameters passed are ([2, 2, 3], [5, 4, 1]), the volume of a is 12 and the volume of b is 20. Therefore, the function should return 8.

Your function will be tested with pre-made examples as well as random ones.

The solution in Java code

Option 1:

interface CuboidVolumes {
  static int findDifference(int[] a, int[] b) {
    return Math.abs(a[0] * a[1] * a[2] - b[0] * b[1] * b[2]);
  }
}

Option 2:

public class CuboidVolumes {
  public static int findDifference(final int[] firstCuboid, final int[] secondCuboid) {
    int vol1 = 1, vol2 = 1;
    for (int i = 0; i < 3; i++) {
      vol1 *= firstCuboid[i];
      vol2 *= secondCuboid[i];
    }
    
    return Math.abs(vol1 - vol2);
  }
}

Option 3:

public class CuboidVolumes {
  public static int findDifference(final int[] firstCuboid, final int[] secondCuboid) {
    if (getMulti(firstCuboid) > getMulti(secondCuboid)) return getMulti(firstCuboid) - getMulti(secondCuboid);
    return getMulti(secondCuboid) - getMulti(firstCuboid);
  }
  
  public static int getMulti(int[] arr) {
    int sum = 1;
    for (int i = 0; i < arr.length; i++) {
      sum *= arr[i];
    }
    return sum;
  }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Test
    public void sampleTestCases() {
        assertEquals(14, CuboidVolumes.findDifference(new int[]{3, 2, 5}, new int[]{1, 4, 4}));
        assertEquals(106, CuboidVolumes.findDifference(new int[]{9, 7, 2}, new int[]{5, 2, 2}));
        assertEquals(30, CuboidVolumes.findDifference(new int[]{11, 2, 5}, new int[]{1, 10, 8}));
        assertEquals(31, CuboidVolumes.findDifference(new int[]{4, 4, 7}, new int[]{3, 9, 3}));
        assertEquals(0, CuboidVolumes.findDifference(new int[]{15, 20, 25}, new int[]{10, 30, 25}));
    }
}