Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if a list numbers are sequential

Tags:

java

oop

I'm working in Java. I have an unordered list of 5 numbers ranging from 0-100 with no repeats. I'd like to detect if 3 of the numbers are sequential with no gap.

Examples:

[9,12,13,11,10] true
[17,1,2,3,5] true
[19,22,23,27,55] false

As for what I've tried, nothing yet. If I were to write it now, I would probably go with the most naive approach of ordering the numbers, then iteratively checking if a sequence exists.

like image 363
roundar Avatar asked Jun 21 '13 12:06

roundar


People also ask

How do you check if the numbers in a list are consecutive numbers?

With numpy diff and sorted The diff function in numpy can find the difference between each of the numbers after they are sorted. We take a sum of this differences. That will match the length of the list if all numbers are consecutive.

What does it mean for numbers to be sequential?

Sequential Numbering is a popular feature on custom-printed forms Sequential Numbering, also known as Consecutive Numbering, refers to the printing of ascending or descending identification numbers so that each printed unit receives its own unique number.


2 Answers

int sequenceMin(int[] set) {
    int[] arr = Arrays.copy(set);
    Arrays.sort(arr);
    for (int i = 0; i < arr.length - 3 + 1; ++i) {
        if (arr[i] == arr[i + 2] - 2) {
            return arr[i];
        }
    }
    return -1;
}

This sorts the array and looks for the desired sequence using the if-statement above, returning the first value.


Without sorting:

(@Pace mentioned the wish for non-sorting.) A limited range can use an efficient "boolean array", BitSet. The iteration with nextSetBit is fast.

    int[] arr = {9,12,13,11,10};
    BitSet numbers = new BitSet(101);
    for (int no : arr) {
        numbers.set(no);
    }
    int sequenceCount = 0;
    int last = -10;
    for (int i = numbers.nextSetBit(0); i >= 0; i = numbers.nextSetBit(i+1)) {
        if (sequenceCount == 0 || i - last > 1) {
            sequenceCount = 1;
        } else {
            sequenceCount++;
            if (sequenceCount >= 3) {
                System.out.println("Sequence start: " + (last - 1));
                break;
            }
        }
        last = i;
    }
    System.out.println("Done");
like image 66
Joop Eggen Avatar answered Sep 24 '22 06:09

Joop Eggen


Very naive (but faster) algorithm : (your array is input[], assuming it only contains 0-100 numbers as you said)

int[] nums=new int[101];
for(i=0;i<N;i++) 
   {
   int a=input[i];
   nums[a]++;
   if (a>0) { nums[a-1]++; }
   if (a<100) { nums[a+1]++; }
   }

Then look if there is an element of nums[]==3.

Could be faster with some HashMap instead of the array (and removes the 0-100 limitation)


Edit : Alas, this does NOT work if two numbers could be equal in the initial sequence

like image 45
Orabîg Avatar answered Sep 22 '22 06:09

Orabîg