I’m a senior in high school taking a computer science class. For homework, we have to create solutions to certain CodingBat (practice coding website) problems. I am experiencing problems with this question, some of which include OutOfBounds for the array. Based on my code, I can’t quite figure out why this is happening. The following attached code (below) is what I have created as a solution to the CodingBat problem for unlucky1 in Array-1 (java), which describes the challenge as: “We'll say that a 1 immediately followed by a 3 in an array is an "unlucky" 1. Return true if the given array contains an unlucky a in the first 2 or last 2 positions in the array.
public boolean unlucky1(int[] nums) {
int i = 0;
for(i = 0; i < nums.length; i )
if(nums[i-1] == 1 && nums[i] == 3)
{
return true;
}
return false;
}
CodePudding user response:
The problem statement is "Return true if the given array contains an unlucky a in the first 2 or last 2 positions in the array.", so you don't even need a loop - you just need to examine the first two and last two elements of the array:
public boolean unlucky1(int[] nums) {
return nums != null &&
nums.length >= 2 &&
(nums[0] == 1 && nums[1] == 3 ||
nums[nums.length - 2] == 1 && nums[nums.length -1] == 3);
}
CodePudding user response:
The following code is the correct method.
0.public static boolean unlucky1(int[] nums){ //Firstly,declare the method
"static"
1. int length = nums.length;//Get the array length.
2.if((nums[0] == 1 && nums[1] == 3) && ( nums[length - 2] == 1 &&
nums[length] -1 == 3)){
3. return true;
}
4. return false;
}
In row 2,your code was: "if(nums[i-1] == 1 && nums[i] == 3)";
It showed arrayoutofbound because the starting array index is 0 and you decalred in the if statement
" if(nums[0-1]...)which says if nums[-1] which is out of bounds."
Also to check the last 2 numbers of the array you do the following:
( nums[length - 1] == 1 && nums[length] == 3)) where :
" nums[length - 2] == 1"
checks 1 value before the last array value
and
" nums[length] - 1 == 3 "
checks the last array value