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; }
public int[] copyEvens(int[] nums, int count) {
ReplyDeleteint[] 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;
}
int index=0;
ReplyDeleteint[] arr = new int[count];
for(int n : nums){
if(n%2==0 && index<count) {
arr[index]=n;
index++;
}
}return arr;
int[] filteredArray = Arrays.stream(nums).filter(n -> n%2==0).toArray();
ReplyDeletereturn Arrays.copyOfRange(filteredArray, 0 ,count);
public int[] copyEvens(int[] nums, int count) {
ReplyDeleteint[] arr = new int[count];
int index = 0;
for(final int n : nums){
if(n % 2 == 0 && index<count) {
arr[index]=n;
index++;
}
}
return arr;
}
With Stream API
ReplyDeletereturn Arrays.stream(nums).filter(x->x%2 ==0).limit(count).toArray();