Find Numbers Which Are Divisible by Given Number in Java


The challenge

Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of numbers and the second is the divisor.

Example

divisibleBy([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6]

The solution in Java

Option 1 (using streams):

import java.util.stream.*;
import java.util.Arrays;

public class EvenNumbers {
  public static int[] divisibleBy(int[] numbers, int divider) {
  
    return Arrays.stream(numbers)
                 .filter(i -> (i % divider) == 0)
                 .toArray();
  }
}

Option 2 (writing the code ourselves):

public class EvenNumbers {
    public static int[] divisibleBy(int[] numbers, int divider) {
        int count = 0;
        for (int number : numbers){
          if (number % divider == 0){
            count ++;
          }
        }
        int[] arr = new int[count];
        int i = 0;        
        for (int number : numbers){
          if (number % divider == 0){
            arr[i] = number;
            i++;
          }        
        }
        return arr;
    }
}

Test cases to validate our code

import java.util.Arrays;
import java.util.Random;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;

public class EvenNumbersTest {
  private static int[] divisibleBy(int[] numbers, int divider) {
    return Arrays.stream(numbers).filter(n -> n % divider == 0).toArray();
  }
  
  @Test public void testSimple() {
    assertArrayEquals(new int[] {2,4,6}, EvenNumbers.divisibleBy(new int[] {1,2,3,4,5,6},2));
    assertArrayEquals(new int[] {3,6}, EvenNumbers.divisibleBy(new int[] {1,2,3,4,5,6},3));
    assertArrayEquals(new int[] {0,4}, EvenNumbers.divisibleBy(new int[] {0,1,2,3,4,5,6},4));
  }
  
  @Test public void testRandom() {
    Random r = new Random();
    for (int i = 0; i < 20; i++) {
      int n = 2 + r.nextInt(10);
      int[] a = r.ints(100,0,100).toArray();
      assertArrayEquals(divisibleBy(a, n), EvenNumbers.divisibleBy(a, n));
    }
  }
}