Skip to content

Instantly share code, notes, and snippets.

@OutOfBrain
Created January 16, 2016 00:41
Show Gist options
  • Select an option

  • Save OutOfBrain/30a155c2633f65840d4a to your computer and use it in GitHub Desktop.

Select an option

Save OutOfBrain/30a155c2633f65840d4a to your computer and use it in GitHub Desktop.
Find all streaks in a sequence of numbers
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class FindStreaks {
public static void main(String[] args) {
int[] array = new int[Integer.MAX_VALUE/32];
Random rand = new Random();
int maxInt = 10000;
for (int i = 0; i < array.length; ++i) {
array[i] = rand.nextInt(maxInt);
}
// array = new int[10];
// array[0] = 1;
// array[1] = 20;
// array[2] = 3;
// array[3] = 4;
// array[4] = 50;
// array[5] = 6;
// array[6] = 7;
// array[7] = 8;
// array[8] = 9;
// array[9] = 90;
final int maxNumDiff = 1000;
final int minStreakLength = 8;
List<List<Integer>> streakList = new ArrayList<>();
int streakStart = 0;
int streakLength = 0;
for (int i = 0; i < array.length-1; ++i) {
// we have no running streak yet - start one
if (streakLength == 0) {
streakStart = i;
}
boolean isStreak = Math.abs(array[i] - array[i+1]) <= maxNumDiff;
if (isStreak) {
// we found a streak - or continue one
++streakLength;
}
if (
!isStreak && streakLength >= 1 // is not a streak but we had one before
|| streakLength >= 1 && i + 2 >= array.length // we have a streak but reached end of data
) {
if (streakLength > minStreakLength) {
// our streak ends now
List<Integer> streakElements = new ArrayList<>();
for (int j = streakStart; j <= streakStart + streakLength; ++j) {
streakElements.add(array[j]);
}
streakList.add(streakElements);
}
streakLength = 0;
}
}
System.out.println("Found " + streakList.size() + " streaks");
for (List<Integer> streakElements : streakList) {
printList(streakElements);
System.out.println("next list");
}
}
private static void printList(List<Integer> streakElements) {
streakElements.forEach(element -> {
System.out.print(element + " ");
});
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment