简体   繁体   中英

How to check if there are 3 consecutive 1s in array in java?

simple example: array[6]

[1 1 1 0 0 0]

It is ok to have 3 of 1s in array but can not be consecutive.

If there are 3 consecutive 1s in a row, return false.

here is my code i am working on. I am trying y-(y-1)-(y-2) ==-1, return false but I cant make it work

Please show me good way to do it

I cannot find solutions on internet so if you know please direct the link.

New fixed: change from int[][]grid to int[] arr. Sorry for confusion

public static boolean checkOK(int[] arr) {
        int limit = 3; //amount of number 1 can hay in each row and column
        int countOne = 0;

            for (int y = 0; y < grid.length; y++) { 
                if (arr[y] == 1) 
                    countOne++; // increment countOnes              
            }

            if (countOne > limit) { // false if amount of value 1 over 3
                return false;
            }

            if (countOne == limit) {
                // checking 3 consecutive 1s in array here?
                    return false;
            }   
        return true;
    } 

for array above output should return false

I think your solution is close (apart from the syntax errors in your post).

The problem is that you are simply counting the number of 1's in the array, then after processing all of the elements in the array checking if there are three.

This would result in you getting a "false" return if there are three 1's anywhere in your array - contiguous or not.

The alternative is to increment the counter if you see a 1 like you are doing, but if you see something else, reset the counter to 0. Then, and this is the important bit, inside your loop check to see if you have reached the limit. If you have, then return false at that time.

The other problem that you might encounter is if your array has less than three elements in it. If you use logic such as array[i] == 1 && array[i-1] == 1... then you will either encounter index out of bounds exceptions and/or more complicated logic trying to avoid those exceptions.

Following is a full working example that addresses both problems.

package sequencechecker;

/**
 * @author gmc
 */
public class SequenceChecker {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SequenceChecker sc = new SequenceChecker();

        int [] data = new int [] {1,1,1, 0, 0, 0};
        sc.test (data);
        data = new int [] { 1, 0, 1, 0, 1, 0};
        sc.test(data);

        data = new int [] {1, 1};
        sc.test(data);
    }

    public void test(int [] array) {
        System.out.print("for: ");
        for (int i : array) {
            System.out.print(i + " ");
        }
        System.out.println(check(array));
    }

    public static final int LIMIT = 3;
    public boolean check(int [] array) {
        int cntr = 0;

        for (int i : array) {
            if (i == 1) {
                cntr++;
            } else {
                cntr = 0;
            }
            if (cntr >= LIMIT) {
                return false;
            }
        }   
        return true;
    } 
}

The output is as follows:

for: 1 1 1 0 0 0 false
for: 1 0 1 0 1 0 true
for: 1 1 true

Keep track of the count of consecutive 1s and exit the loop if you hit 3.

static boolean checkOK(int[] arr)
{       
    int count = 0;
    for(int i=0; count < 3 && i < arr.length; i++)
        count = (arr[i] == 1) ? count + 1 : 0;
    return count < 3;
}

Test

int[][] tests = {
        {},
        {1},
        {1,1},
        {1,1,1},
        {0,1,1,1},
        {1,1,1,0},
        {0,1,1,1,0},
        {0,1,0,1,0}
};

for(int[] test : tests)
    System.out.format("%s : %s%n", Arrays.toString(test), checkOK(test));

Output:

[] : true
[1] : true
[1, 1] : true
[1, 1, 1] : false
[0, 1, 1, 1] : false
[1, 1, 1, 0] : false
[0, 1, 1, 1, 0] : false
[0, 1, 0, 1, 0] : true

Does my code work for your problem?

int[] grid = new int[]{1,1,1,0,0,0};
        for (int y = 0; y < grid.length - 2; y++) {
            if (grid[y] == 1 && grid[y] == grid[y+1] && grid[y] == grid[y+2]) return false;
        }

I'm not sure if the method needs to check if there are at least three, or if there are exactly three. This one is for at least three 1s (I don't have enough reputation to ask via comment).
This is the most straight foward approach I could think of, just having a counter and checking if it got to 3.

int countOne = 0;
for (int y = 0; y < grid.length && countOne < 3; y++) {
    if (grid[y] == 1) 
        countOne++;
    else
        countOne = 0;
}
return countOne != 3;

One could at first put the countOne < 3 as a condition inside the loop with a break, as follows:

int countOne = 0;
for (int y = 0; y < grid.length; y++) {
    if (grid[y] == 1) {
        countOne++;
        if (countOne == 3)
            return false;
    }
    else
        countOne = 0;
}
return true;

It's just that my teachers always insisted on not putting breaks inside loops unless you really need to.
The last return is true because there's no way to get out of the loop with three 1s as the method already returned false inside.

Try this.

int[] ar = {1,1,2,1,2,2,2,1,2,1,2,1,1,1,2,1,2,1,1};
System.out.println(isValid(ar));
int[] ar1 = {1,1,2,1,2,2,2,1,2,1,2,1,1,2,1,2,1,1};
System.out.println(isValid(ar1));

Prints

false
true
  • This simply counts up to three. If a digit not 1 is encountered, the count is reset to 0.
  • as soon as three consecutive 1's are found, the method returns false.
public static boolean isValid(int[] arr) {
    int count = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == 1) {
            count++;
            if (count == 3) {
                return false;
            }
        } else {
            count = 0;
        }
    }
    return true;
}

Try this one:

public static void main(String args[]) {
    int[] array = new int[]{1, 1, 1, 0, 0, 0};
    System.out.println("IS OK? : " + checkOK(array));
}

public static boolean checkOK(int[] array) {
    for(int i = 0; i < array.length; i++) {
        if(!valid(array, i))
            return false;
    }

    return true;
}

static boolean valid(int[] array, int index) {
    if(index < 1 || index >= array.length - 1)
        return true;

    return !(array[index - 1] == array[index] && array[index] == array[index + 1]);
}

You can try this simple algorithm that increments if the item equals to one and reset it is zero, then check if the count greater than or equal to exceed then return false

    public static boolean checkOK(int[] arr, int exceed) {
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == 1) count++;
            else count = 0;
            if (count >= exceed)
                return false;
        }
        return true;
    }

, Main

    public static void main(String[] args) {
        System.out.println(checkOK(new int[] { 1, 1, 1, 0, 0, 0 }, 3));
        System.out.println(checkOK(new int[] { 1, 0, 0, 1, 1, 1 }, 3));
        System.out.println(checkOK(new int[] { 0, 1, 0, 1, 0 }, 3));
        System.out.println(checkOK(new int[] { 0, 1, 1, 1, 0 }, 3));
    }

, output

false
false
true
false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM