Skip to content

Instantly share code, notes, and snippets.

@Unix-Code
Created December 11, 2015 14:57
Show Gist options
  • Save Unix-Code/e8a8bb9349bb93a2ea3d to your computer and use it in GitHub Desktop.
Save Unix-Code/e8a8bb9349bb93a2ea3d to your computer and use it in GitHub Desktop.
import java.util.Date;
import java.util.Random;
public class ArrayRepetitionFinder {
public static void main(String[] args) {
//int[] array = new int[100000000];
Random rand = new Random();
long[] times = new long[10];
/*for (int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(9) + 1;
}*/
Integer[] array2 = new Integer[100000000];
for (int i = 0; i < array2.length; i++) {
array2[i] = rand.nextInt(9) + 1;
}
Date start;
Date end;
long duration;
for (int i = 0; i < 10; i++) {
if (i < 4) {
start = new Date();
find(array2);
end = new Date();
duration = end.getTime() - start.getTime();
System.out.println(duration);
times[i] = duration;
}
else {
start = new Date();
find2(array2);
end = new Date();
duration = end.getTime() - start.getTime();
System.out.println(duration);
times[i] = duration;
}
}
long[] Sum = {0, 0};
for (long time : times) {
System.out.print(time + ", ");
}
System.out.println("");
for (int i = 0; i < times.length; i++) {
if (i < times.length/2) {
Sum[0] += times[i];
}
else if (i >= times.length/2){
Sum[1] += times[i];
}
}
System.out.println(Sum[0] + ", " + Sum[1]);
System.out.println("Averages: " + Sum[0]/(times.length/2) + ", " + Sum[1]/(times.length/2));
}
public static int find(Integer[] array) {
int counter = 1;
int countTemp = 0;
int iTemp = -1;
Integer current;
Integer next;
for (int i = 0; i < array.length; i++) {
current = array[i];
next = (i + 1 == array.length) ? null : array[i + 1];
if (next == current) {
counter++;
}
else if (next != current && counter > 1) {
if (counter > countTemp) {
iTemp = i - counter + 1;
countTemp = counter;
}
counter = 1;
}
}
return iTemp;
}
public static int find2(Integer[] array) {
int counter = 1;
int countTemp = 0;
int iTemp = 0;
int retIndex = -1;
Integer current = null;
for (int i = 0; i < array.length; i++) {
if (array[i] == current) {
counter++;
}
else {
if (counter > countTemp) {
countTemp = counter;
retIndex = iTemp;
}
counter = 1;
iTemp=i;
current = array[i];
}
}
if (counter > countTemp && retIndex != -1) {
retIndex = iTemp;
}
return retIndex;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment