Java > Array-2 > twoTwo

1.1k views Asked by At

problem

Given an array of ints, return true if every 2 that appears in the array is next to another 2.

  • twoTwo({4, 2, 2, 3})true

  • twoTwo({2, 2, 4})true

  • twoTwo({2, 2, 4, 2})false

my code is only mising this case

twoTwo({2, 2, 7, 2, 1}) → false; but returns true;

my code

public boolean twoTwo(int[] nums) {
    int notFound = 0;
    int i = 0;
    boolean found = false;
    if (nums.length == 0) {
        return true;
    }
    if (nums.length == 1 && (nums[0] != 2)) {
        return true;
    }

    for (i = 0; i < nums.length - 1; i++) {

        if ((nums[i] == 2 && nums[i + 1] == 2)) {
            found = true;
        }
        if (nums[nums.length - 1] == 2 && nums[nums.length - 2] != 2) {
            return false;
        }
        if (nums[i] != 2) {
            notFound++;
        }


    }

    if (nums[i] != 2) {
        notFound++;
    }

    if (notFound == nums.length) {
        return true;
    }
    return found;
}
2

There are 2 answers

7
lmcphers On BEST ANSWER

There is never a "wrong" way to code a working solution, but there are bad ways. In your solution, I think you try to handle every individual case in chaotic ways instead of tackling the overarching problem. You have floating variables all over the place and hard coded numbers that are very specific to each case. You have unnecessary and excessive returns.

My suggestion is to work on solving your own question "Return true if all 2's are next to another 2" - instead of trying to code for each specific case. You aren't REALLY solving a problem if you are hard coding to work on a specific subset of that problem.

Just my critique; keep working at it.

Consider refactoring your for loop with this as a starting point, see if you can figure out the logic (semi pseudo code):

for(int i = 1; i < nums.length-1; i++) { // Why do I start i at 1?
  if(nums[i]==2) {
    if(nums[i-1] == 2 || nums[i+1] == 2) // What does this if check?
      do something; // What to do here?  Look up the 'continue' keyword.
    else
      return false;
  }
}
return true;

You will find this for loop is JUST a starting point. There will be more needed to add, but hopefully a good jumping point for you.

Best of luck!

11
Jashaszun On
public boolean twoTwo(int[] nums)
{
    if (nums.length == 1 && nums[0] == 2)
        return false;

    for (int i = 0; i < nums.length - 1; i++)
        if (nums[i] == 2)
            if (nums[i + 1] != 2 && (i > 0 && nums[i - 1] != 2))
                return false;
    return true;
}

Basically this goes through each number in the list, and if it finds a 2, it checks it against the previous and next numbers. That's all it does.