Java > AP-1 > copyEvens (CodingBat Solution)

Problem:

Given an array of positive ints, return a new array of length "count" containing the first even numbers from the original array. The original array will contain at least "count" even numbers.

copyEvens({3, 2, 4, 5, 8}, 2) → {2, 4}
copyEvens({3, 2, 4, 5, 8}, 3) → {2, 4, 8}
copyEvens({6, 1, 2, 4, 5, 8}, 3) → {6, 2, 4}


Solution:

public int[] copyEvens(int[] nums, int count) {
  int ctr = 0;
  int[] array = new int[count];
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] % 2 == 0) {
      array[ctr] = nums[i];
      ctr++;
    }
      if (ctr == count)
        return array;
  }
  return nums;
}


5 comments :

  1. public int[] copyEvens(int[] nums, int count) {
    int[] result = new int[count];
    int counter = 0;
    for(int i=0; i<nums.length && counter<count; i++)
    {
    if(nums[i]%2==0)
    {
    result[counter]=nums[i];
    counter++;
    }
    }
    return result;
    }

    ReplyDelete
  2. int index=0;
    int[] arr = new int[count];
    for(int n : nums){
    if(n%2==0 && index<count) {
    arr[index]=n;
    index++;
    }
    }return arr;

    ReplyDelete
  3. int[] filteredArray = Arrays.stream(nums).filter(n -> n%2==0).toArray();
    return Arrays.copyOfRange(filteredArray, 0 ,count);

    ReplyDelete
  4. public int[] copyEvens(int[] nums, int count) {
    int[] arr = new int[count];
    int index = 0;
    for(final int n : nums){
    if(n % 2 == 0 && index<count) {
    arr[index]=n;
    index++;
    }
    }
    return arr;
    }

    ReplyDelete
  5. With Stream API

    return Arrays.stream(nums).filter(x->x%2 ==0).limit(count).toArray();

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact