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.

Example:

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

You must not mutate the original array.

The solution in Java code

Option 1:

import static java.util.stream.IntStream.of;
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();
  }
}

Option 2:

import java.util.Arrays;
import java.util.function.Function;

public class Solution {
  public static Function<Integer, int[]> multiplyAll(int[] array) {
    return (n) -> Arrays.stream(array).map(x -> x*n).toArray();
  }
}

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 = Arrays.stream(array).map(v -> v * n).toArray();
            assertArrayEquals(expected, Solution.multiplyAll(array).apply(n));
        }
    }
}