Algebra/consecutive number
Expert: David Montiel - 9/11/2009
QuestionDavid,
I am a cobol programmer and have a unique problem.
I want to be able to determine if a sequence of 9 digits are sequential.
for example,
123456789 is sequential
987654321 is also sequential
456789012 is also sequential
012345678 is sequential
234567890 is sequential etc
234567891 is NOT sequential, etc
any ideas you have would be appreciated.
thank you,
Dave
AnswerHello Dave,
OK, you say you have a 9 digit number so I am going to assume that this is always the case. I'm also going to assume that you can separate each digit into a separate variable (if this is not the case let me know and I'll think of a way to do this).
So, to begin with, you should be able to write all digits in an array of 9 entries. Let's call this array "x". Consider, for instance, the sequential number:
n=789012345
So the entries of your array will be:
x(1)=7, x(2)=8, x(3)=9, x(4)=0, x(5)=1, ... , x(9)=5
So far so good?
I notice that you are considering both "forward" (as in the example) and "reverse" (e.g. 876543210) sequences.
For forward sequences, notice that the difference between an entry and the previous entry is always "1" or "-9". For instance, considering the example above:
x(2)-x(1) = 8-7 = 1,
x(3)-x(2) = 9-8 = 1,
.
.
.
And
x(4)-x(3) = 0-9 = -9
Notice also that there can only be one "-9", namely the jump from 9 to 0.
So all you would have to do is make a loop from entry #2 to entry #9 where you take the difference.
x(i)-x(i-1)
and verify that this gives you get either "1" or "-9" at every step (BTW you don't have to worry about having more than one "-9" because that would imply having a jump higher than "1" elsewhere). If this is satisfied all the way to the end of the loop, then you have forward sequence and you're done. If it is not satisfied at least in one the steps, then you don't have a forward sequence.
Suppose you don't have a forward sequence, then you still have to check for the possibility that the sequence is backwards. All you need to do is repeat the loop above but expecting all entries to be either "-1" or "9". instead of "1" or "-9" Do you see why?
If your array turn out to be neither forward not backward sequential then your number is definitely NOT sequential.
Hope this helps but let me know if you are still stuck.
Cheers,
David