我需要确定数字列表是否按真实顺序排列。特别是5的序列。
示例 1:
- (原创系列)
1,3,4,67,43,20
- (订购系列)
1,3,4,20,43,67
- 是5的序列吗?
FALSE
示例 2
- (原创系列)
147,10,143,432,144,23,145,146
- (订购系列)
10,23,143,144,145,146,147,432
- 是5的序列吗?
TRUE
(即 143-147)
目前 - 我遍历有序列表,并检查当前数字是否等于最后一个数字 +1,并保留一个计数器。这行得通,但我很好奇是否有更好的方法来数学或编程。
<cfscript>
_list1 = [1,3,4,67,43,20]; // should evaluate to FALSE
_list2 = [147,10,143,432,144,23,145,146]; // should evaluate to TRUE
_list = _list2; // switch list in one place - test purposes only.
_seq = 1; // sequence counter
_cap = ''; // value of the upper most number of the sequence
_msg = 'There is not a consecutive sequence of 5.'; // message to user
// sort the array smallest to largest
arraySort( _list, 'numeric' );
// loop the array - compare the last number with the current number
for ( i=2; i LTE arrayLen( _list ); i++ ) {
_last = _list[i-1]; // the LAST number - we started at the second element, so we shouldn't error.
_this = _list[i]; // this current number
// compare the two numbers
if ( val( _this ) EQ val( _last ) + 1 ) {
_seq = _seq + 1; // increment our sequence
_cap = _this; // set the top number
}
}
// re-set the message if we meet some threshold (5) is hardcoded here
if ( val( _seq ) GTE 5 ) {
_msg = 'Sequence of ' & _seq & ' to ' & _cap;
}
// write the message
writeoutput( _msg );
</cfscript>