Description:
You have been asked to work out the area of number of rectangles.
The input to your function is a array of longs. If the arrays length is odd you should return void. Otherwise you should use adjacent pairs of longs to calculate the area.
For example if the input is {4,4,5,5,6,6,7,7} you should return {16, 25, 36, 49}.
public class Area { public static long[] workOutArea(final long[] values){ if (values.length % 2 != 0) { return null; // This is ugly! } else { final long[] areas = new long[values.length / 2]; for (int i = 0; i < values.length; i += 2) { areas[i / 2] = values[i] * values[i + 1]; } return areas; } } }
- public class Area {
public static long[] workOutArea(long[] values){- public static long[] workOutArea(final long[] values){
- if (values.length % 2 != 0) {
- return null; // This is ugly!
- } else {
- final long[] areas = new long[values.length / 2];
- for (int i = 0; i < values.length; i += 2) {
- areas[i / 2] = values[i] * values[i + 1];
- }
- return areas;
- }
- }
- }
import org.junit.Test; import org.junit.Assert; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testValidInput() { long[] val1 = {4L, 4L, 5L, 5L, 6L, 6L, 7L, 7L}; long[] expected = {16L, 25L, 36L, 49L}; Assert.assertArrayEquals(Area.workOutArea(val1), expected); } @Test public void testInvalidInput() { long[] val2 = {4L, 4L, 5L, 5L, 6L, 6L, 7L}; Assert.assertEquals(Area.workOutArea(val2), null); } @Test public void testEmptyInput() { long[] empty = {}; Assert.assertArrayEquals(empty, new long[] {}); } }
- import org.junit.Test;
- import org.junit.Assert;
- import static org.junit.Assert.assertEquals;
- import org.junit.runners.JUnit4;
- public class SolutionTest {
- @Test
- public void testValidInput() {
- long[] val1 = {4L, 4L, 5L, 5L, 6L, 6L, 7L, 7L};
- long[] expected = {16L, 25L, 36L, 49L};
- Assert.assertArrayEquals(Area.workOutArea(val1), expected);
- }
- @Test
- public void testInvalidInput() {
- long[] val2 = {4L, 4L, 5L, 5L, 6L, 6L, 7L};
- Assert.assertEquals(Area.workOutArea(val2), null);
- }
- @Test
public void testSomething() {long[] val1 = {4l,4l,5l,5l,6l,6l,7l,7l};Assert.assertArrayEquals(area.workOutArea(val1), new long[] {16l, 25l, 36l, 49l});long[] val2 = {4l,4l,5l,5l,6l,6l,7l};assertEquals(null, area.workOutArea(val2));- public void testEmptyInput() {
- long[] empty = {};
- Assert.assertArrayEquals(empty, new long[] {});
- }
}- }