diff --git a/produto-do-array/MultiplyArray.java b/produto-do-array/MultiplyArray.java new file mode 100644 index 0000000..c22c25b --- /dev/null +++ b/produto-do-array/MultiplyArray.java @@ -0,0 +1,25 @@ +import java.util.ArrayList; +import java.util.List; + +public class MultiplyArray { + + public List multiply(List numbers) { + + if (numbers.isEmpty()) throw new IllegalArgumentException(); + List result = new ArrayList<>(); + + Long prefix = 1L; + for (int i = 0; i < numbers.size(); i++) { + result.add(prefix); + prefix *= numbers.get(i); + } + + Long suffix = 1L; + for (int i = numbers.size() - 1; i >= 0; i--) { + result.set(i, result.get(i) * suffix); + suffix *= numbers.get(i); + } + + return result; + } +} diff --git a/produto-do-array/MultiplyArrayTest.java b/produto-do-array/MultiplyArrayTest.java new file mode 100644 index 0000000..355fb86 --- /dev/null +++ b/produto-do-array/MultiplyArrayTest.java @@ -0,0 +1,56 @@ +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +public class MultiplyArrayTest { + + private MultiplyArray multiplyArray; + + @BeforeEach + public void setUp() { + multiplyArray = new MultiplyArray(); + } + + @Test + public void shouldReturnNewArrayOfMultiplyAllElementsInArray() { + List expected = new ArrayList<>(List.of(120L, 60L, 40L, 30L, 24L)); + List request = new ArrayList<>(List.of(1, 2, 3, 4, 5)); + + List result = multiplyArray.multiply(request); + + assertNotNull(result); + assertEquals(expected, result); + } + + @Test + public void shouldReturnEmptyNewArrayWhenArrayEmpty() { + List requestArray = new ArrayList<>(); + assertThrows(IllegalArgumentException.class, () -> multiplyArray.multiply(requestArray)); + } + + @Test + public void shouldReturnNewArrayWhenContainOneZero() { + List expected = new ArrayList<>(List.of(0L, 8L, 0L)); + List request = new ArrayList<>(List.of(2, 0, 4)); + + List result = multiplyArray.multiply(request); + + assertNotNull(result); + assertEquals(expected, result); + } + + @Test + public void shouldReturnAllZerosNewArrayWhenContainTwoOrMoreZero() { + List expected = new ArrayList<>(List.of(0L, 0L, 0L, 0L)); + List request = new ArrayList<>(List.of(2, 0, 4, 0)); + + List result = multiplyArray.multiply(request); + + assertNotNull(result); + assertEquals(expected, result); + } +} diff --git a/produto-do-array/pom.xml b/produto-do-array/pom.xml new file mode 100644 index 0000000..2864c4c --- /dev/null +++ b/produto-do-array/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + + com.gabriel + produto-do-array + 1.0-SNAPSHOT + + + 17 + 17 + + + + + + org.junit.jupiter + junit-jupiter + 5.10.2 + test + + + + + + ${project.basedir} + ${project.basedir} + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.2.5 + + false + + + + + \ No newline at end of file