Multiply all elements in an array in Java

The challenge

Create a function multiplyAll/multiply_all which takes an array of integers as an argument. This function must return another function, which takes a single integer as an argument and returns a new array.

The returned array should consist of each of the elements from the first array multiplied by the integer.


multiplyAll([1, 2, 3])(2) = [2, 4, 6];

You must not mutate the original array.

The solution in Java code

Option 1:

import static; import java.util.function.Function; public class Solution { public static Function<Integer,int[]> multiplyAll(int[] array) { return i -> of(array).map(a -> a*i).toArray(); } }
Code language: Java (java)

Option 2:

import java.util.Arrays; import java.util.function.Function; public class Solution { public static Function<Integer, int[]> multiplyAll(int[] array) { return (n) -> -> x*n).toArray(); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; class SolutionTest { @Test void isArray() { assertEquals(int[].class, Solution.multiplyAll(new int[]{1}).apply(1).getClass()); } @Test void hasCorrectLength() { assertEquals(2, Solution.multiplyAll(new int[]{1, 2}).apply(1).length); } @Test void basicTests() { assertArrayEquals(new int[]{1, 2, 3}, Solution.multiplyAll(new int[]{1, 2, 3}).apply(1)); assertArrayEquals(new int[]{2, 4, 6}, Solution.multiplyAll(new int[]{1, 2, 3}).apply(2)); assertArrayEquals(new int[]{0, 0, 0}, Solution.multiplyAll(new int[]{1, 2, 3}).apply(0)); assertArrayEquals(new int[0], Solution.multiplyAll(new int[0]).apply(10), "should return an empty array"); } @Test void randomTests() { ThreadLocalRandom rnd = ThreadLocalRandom.current(); for(int i = 0; i < 200; ++i) { int l = rnd.nextInt(10); int[] array = rnd.ints(0, 100).limit(l).toArray(); int n = rnd.nextInt(100); int[] expected = -> v * n).toArray(); assertArrayEquals(expected, Solution.multiplyAll(array).apply(n)); } } }
Code language: Java (java)
Notify of
Inline Feedbacks
View all comments