Created
May 14, 2014 13:22
-
-
Save MauroMombelli/b68641a785f3e93fd410 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
public class ZeroSeriesLength { | |
public static void main(String[] args) throws Exception { | |
int maxLength; | |
long nanoTime; | |
for (int i = 0; i < 100; i++) { | |
Random r = new Random(); | |
int size = 10000; | |
int[] values = new int[size]; | |
for (int a=0;a<size;a++){ | |
values[a] = r.nextInt(10); | |
} | |
System.out.println("Array size: " + size ); | |
nanoTime = System.nanoTime(); | |
maxLength = getMax(values); | |
nanoTime = System.nanoTime() - nanoTime; | |
System.out.println("Method 1: Maximum number of consecutive zeros : " + maxLength + " nanos: " + nanoTime); | |
int tmpLength = maxLength; | |
nanoTime = System.nanoTime(); | |
maxLength = getMax2(values); | |
nanoTime = System.nanoTime() - nanoTime; | |
System.out.println("Method 2: Maximum number of consecutive zeros : " + maxLength + " nanos: " + nanoTime); | |
if(tmpLength != maxLength){ | |
System.out.println("WRONG ALGORITHM.. array is: "); | |
for (int a:values){ | |
System.out.print(a+", "); | |
} | |
System.out.println(); | |
System.exit(-1); | |
} | |
} | |
} | |
private static int getMax(int[] values) { | |
int maxLength = 0; | |
for (int i = 0; i < values.length; i+=1+maxLength) { // here we are looking for the first zero. if lenght remaining is lesser than actual max zero-strike, no way we caund found a better. | |
if (values[i] == 0) { // is zero | |
//find leftmost zero | |
int tmpLeft = 0; | |
while(tmpLeft < i && values[i-tmpLeft-1] == 0){ | |
tmpLeft++; | |
} | |
//find righmost zero | |
int tmpRight = 0; | |
while(tmpRight+i < values.length && values[i+tmpRight] == 0){ | |
tmpRight++; | |
} | |
maxLength = Math.max(maxLength, tmpLeft+tmpRight); | |
} | |
} | |
return maxLength; | |
} | |
public static int getMax2(int[] values) { | |
int maxLength = 0; | |
int tempLength = 0; | |
for (int i = 0; i < values.length; i++) { | |
if (values[i] == 0) { | |
tempLength++; | |
} else { | |
tempLength = 0; | |
} | |
if (tempLength > maxLength) { | |
maxLength = tempLength; | |
} | |
} | |
return maxLength; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment