Java > AP-1 > copyEndy (CodingBat Solution)

Problem:

We'll say that a positive int n is "endy" if it is in the range 0..10 or 90..100 (inclusive). Given an array of positive ints, return a new array of length "count" containing the first endy numbers from the original array. Decompose out a separate isEndy(int n) method to test if a number is endy. The original array will contain at least "count" endy numbers.

copyEndy({9, 11, 90, 22, 6}, 2) → {9, 90}
copyEndy({9, 11, 90, 22, 6}, 3) → {9, 90, 6}
copyEndy({12, 1, 1, 13, 0, 20}, 2) → {1, 1}


Solution:

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

private boolean isEndy(int n) {
  return (n >= 0 && n <= 10) || (n <= 100 && n >= 90);
}

4 comments:

  1. public int[] copyEndy(int[] nums, int count) {
    int j = 0;
    int[] intArray = new int[count];
    for (int num : nums) {
    if (inRange(num)) {
    intArray[j] = num;
    j++;
    }
    if (j == count)
    break;
    }
    return intArray;
    }
    private boolean inRange(int n) {
    return (n >= 0 && n <= 10) || (n <= 100 && n >= 90);
    }

    ReplyDelete
  2. With Java Stream

    public int[] copyEndy(int[] nums, int count) {
    return Arrays.stream(nums)
    .filter(n -> isEndy(n))
    .limit(count)
    .toArray();
    }

    private boolean isEndy(int n) {
    return (n >= 0 && n <= 10) || (n <= 100 && n >= 90);
    }

    ReplyDelete
  3. public int[] copyEndy(int[] nums, int count) {

    int res[] = new int[count];
    int x = 0;

    for (int j = 0; j < nums.length; j++) {
    if ((nums[j] >= 0 && nums[j] <= 10) || (nums[j] >= 90 && nums[j] <= 100)){
    res[x] = nums[j];
    x = x + 1;
    }
    if (x == count) {
    break;
    }
    }
    return res;
    }

    ReplyDelete
  4. With Stream API

    return Arrays.stream(nums).filter(x->(x>=0 && x<=10) || (x>=90 && x<=100)).limit(count).toArray();

    ReplyDelete