Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array-1 CodingBat unlucky1 (java) Challenge

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading