Sunday, June 5, 2016

Java Challenge - array123 - warm_up_2

Given an array of ints, return true if .. 1, 2, 3, .. appears in the array somewhere.

array123([1, 1, 2, 3, 1]) → true
array123([1, 1, 2, 4, 1]) → false
array123([1, 1, 2, 1, 2, 3]) → true

Hisoka :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public boolean array123(int[] nums) {
  boolean satu=false,dua=false,tiga = false;
  for(int a:nums)
  {
    if(a == 1)satu = true;
    else if(a == 2) dua = true;
    else if(a == 3) tiga = true;   
  }
  return satu && dua && tiga;
}

Hasil :
Codingbat:

1
2
3
4
5
6
7
public boolean array123(int[] nums) {
  // Note: iterate < length-2, so can use i+1 and i+2 in the loop
  for (int i=0; i < (nums.length-2); i++) {
    if (nums[i]==1 && nums[i+1]==2 && nums[i+2]==3) return true;
  }
  return false;
}

Java Challenge - arrayFront9 - warm_up_2

Given an array of ints, return true if one of the first 4 elements in the array is a 9. The array length may be less than 4.

arrayFront9([1, 2, 9, 3, 4]) → true
arrayFront9([1, 2, 3, 4, 9]) → false
arrayFront9([1, 2, 3, 4, 5]) → false
Hisoka :
1
2
3
4
5
6
7
8
public boolean arrayFront9(int[] nums) {
  for(int i=0; i<nums.length; i++)
  {
    if (i > 3)break;
    if (nums[i] == 9) return true;
  }
  return false;
}

Hasilnya :

Codingbat:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public boolean arrayFront9(int[] nums) {
  // First figure the end for the loop
  int end = nums.length;
  if (end > 4) end = 4;
  
  for (int i=0; i<end; i++) {
    if (nums[i] == 9) return true;
  }
  
  return false;
}