# Thread: Consecutive null valors identifier - Suggestions

1. Member
Join Date
Jan 2012
Posts
9
Rep Power
0

## Consecutive null valors identifier - Suggestions

Hi all,
I'm trying to write a boolean method that examines an Array and checks if there are n consecutive null values in it. So if i've got an array called test like this:[2, null, null, 67, 31, null, null, null, 5] and I call test.consecutives(3) it should return true, but if i call test.consecutives(4) it should give me false. Method below for reference.
Now this method actually works (or seems so), I made it by myself, but I think it's a lot messy. Do you think there's a better way to write it?

Java Code:
```public boolean consecutives(int n)
{
int t=0;
for (int i=0; i<arrayLenght-(n+1); i++)
{
for(int k=0; k<=n; k++)
if (arrayName[i+k] == null)
t++;
if (t==n+1)
return true;
}
return false;
}```

2. ## Re: Consecutive null valors identifier - Suggestions

You could split your method up into smaller methods. Perhaps a helper method that only tests whether there are n nulls at some index in an array?

3. ## Re: Consecutive null valors identifier - Suggestions

Suppose that you have found k values equal to null, for k < n; the search started at position i; the next location to start your search is i+k+1, not i+1 as in your implementation. If you have found n values equal to null, your algorithm can terminate.

kind regards,

Jos

4. Member
Join Date
Jan 2012
Posts
9
Rep Power
0

## Re: Consecutive null valors identifier - Suggestions

Originally Posted by JosAH
Suppose that you have found k values equal to null, for k < n; the search started at position i; the next location to start your search is i+k+1, not i+1 as in your implementation. If you have found n values equal to null, your algorithm can terminate.

kind regards,

Jos
Thank you but actually I don't know how to make the for loop to skip k values and start at i+k+1 instead of i+1.
Also, I noticed there's some error in my code so the working one should be this:
Java Code:
```public boolean consecutives(int n)
{
int t=0;
for (int i=0; i<arrayLenght-(n+1); i++)
{
for(int k=0; k<n; k++)  //Modified k<=n in k<n
if (arrayName[i+k] == null)
t++;
if (t==n)                  //Modified t==n+1 in t==n
return true;
}
return false;
}```

5. ## Re: Consecutive null valors identifier - Suggestions

Originally Posted by Bonfy
Thank you but actually I don't know how to make the for loop to skip k values and start at i+k+1 instead of i+1.
Give it a try, because that small change changes the big-Oh performance from O(n^2) to O(n).

kind regards,

Jos

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•