Reputation: 65
I am doing some codingbat challenges for java. In one challenge, you are to return true if the given array in its first 2 or last 2 elements have a 1 followed by a 3.
Example:
unlucky1([1, 3, 4, 5]) → true
unlucky1([2, 1, 3, 4, 5]) → true
unlucky1([1, 1, 1]) → false
As such, I have the following:
for(int i=0, j=nums.length-1; i<nums.length-1; i++, j--) {
if((i<3&&nums[i]==1&&nums[i+1]==3)) {
return true;
}
else if(j>3&&nums[j]==3&&nums[j-1]==1) {
return true;
}
}
return false;
My question is, is there a better way to set the conditions? I do not like the idea of checking if the iterating variables are less than / greater than a constant. My code passes for all of their tests but one, however I feel that it is flawed/messy. How can I efficiently check if the last two & first two indexes have a 1 followed by a 3 without checking if j>3
or i<3
?
The test that it does not pass is with the following array: [1, 1, 1, 3, 1]
My code returns true when the test is supposedly false.
Upvotes: 0
Views: 65
Reputation: 44834
Don't use any loops, edited as per shmosels comment
if (arr[0] == 1 && arr[1] == 3 ||
arr[1] == 1 && arr[2] == 3 ||
arr [arr.length -2] == 1 && arr[arr.length - 1] == 3)
return true;
Upvotes: 1