# determine longest group of consecutive numbers

INPUT:

• 10 random numbers
• each number is greater than 0 and less than 100
• list of numbers is presorted, lowest to highest
• the list will not contain any duplicate numbers

CHALLENGE:

Write a function that would take in the numbers, and return the count of the longest group of consecutive numbers.

EXAMPLE OUTPUT:

1 2 33 44 55 66 77 88 90 98 => return of the function would be 2
1 3 23 24 30 48 49 70 75 80 => return of the function would be 2
6 9 50 51 52 72 81 83 90 92 => return of the function would be 3


## APL, 26 21 characters

1+⌈/+/^\9 9⍴0,1=-2-/⎕


Here's the 26-character solution:

i←⎕⋄⌈/{1++/^\⍵↓1=-2-/i}¨⍳9


I used Dyalog APL as my interpreter, and ⎕IO should be set to 0 for the 26-character version.

Example:

      1+⌈/+/^\9 9⍴0,1=-2-/⎕
⎕:
6 7 51 51 53 51 54 55 56 55
3


This answer explains most of what I in the 26-character solution, but I might have to write a new one up for the 21-character version.

import List
f=maximum.map length.group.zipWith(-)[1..]

• It's not a golf challenge. Please visit this meta thread: meta.codegolf.stackexchange.com/q/456/373 – user unknown Jan 10 '12 at 7:08
• @user unknown: what challenge is it, then? – J B Jan 10 '12 at 10:42
• Ask Bromide. I didn't came up with it. – user unknown Jan 10 '12 at 14:21
• @user unknown: he was already asked; he declined to answer. In the meantime, this is an algorithm question with no scoring criterion; there's no reason why I shouldn't restrict myself to short answers in my answer. I'd upvote yours as well if you gave an explicit reason to. – J B Jan 10 '12 at 17:06
• Well - I don't want to discuss this with 10 different persons in the comments, so I started this thread on meta. Would it mind you, to repeat your argument there? I'm not interested in your particular answer here, but in the general case. See how others count their code size too. I guess a lot just repeat what they see, and believe it is a CG. – user unknown Jan 10 '12 at 19:51

~]1\{.@-(!@*).@}*;]$)p;  Test cases: "1 2 33 44 55 66 77 88 98" --> 2 "1 3 23 24 30 48 49 70 80" --> 2 "6 9 50 51 52 72 81 83 92" --> 3  • It's not a golf challenge. Please visit this meta thread: meta.codegolf.stackexchange.com/q/456/373 – user unknown Jan 10 '12 at 7:07 • @user unknown: When arguing that against a GolfScript submission, you ought to make it clear that you're complaining about the explicit character count, not the language. – J B Jan 10 '12 at 23:29 • @JB: I thought it is clear from the meta thread. – user unknown Jan 11 '12 at 0:03 # Jelly, 5 bytes _JŒɠṀ  Try it online! _J Subtract [1,2,3…] from the input. This will turn a run like [48,49,50] into something like [45,45,45]. Œɠ Get group lengths. (“aaaabbc” → [4,2,1]) Ṁ Maximum.  # J, 23 >:>./(+*[)/\.(}.=>:&}:)  Sample use:  >:>./(+*[)/\.(}.=>:&}:) 1 2 33 44 55 66 77 88 98 2 >:>./(+*[)/\.(}.=>:&}:) 1 3 23 24 30 48 49 70 80 2 >:>./(+*[)/\.(}.=>:&}:) 6 9 50 51 52 72 81 83 92 3  ## Python, 79 characters f=lambda l:max(map(len,''.join(' x'[a-b==1]for a,b in zip(l[1:],l)).split()))+1  • It's not a golf challenge. Please visit this meta thread: meta.codegolf.stackexchange.com/q/456/373 – user unknown Jan 10 '12 at 7:08 • @userunknown: Indeed it's not. However, it is such a trivial boring question that is much more fun to treat as code golf, and so I did so. – Steven Rumbalski Jan 10 '12 at 15:24 ## Mathematica, 50 31 bytes Max[Length/@Split[#,#2-#==1&]]&  This is an anonymous function. You can either give it a name, by assigning it to something, or you can just append @{6, 9, 50, 51, 52, 72, 81, 83, 90, 92} to use it straight away. Here is how it works: #2-#==1& is a nested anonymous function, which takes two arguments and returns True if the arguments are consecutive integers (and False for other integer pairs). Split then partitions the resulting array into runs of elements, for which the above function returns True. Now we map Length onto the result to figure out how many numbers each run contains, and select the maximum. Thanks to David Carraher for eliminating large parts by using a test function in Split! • You can save 19 chars by eliminating RotateLeft and Cases: Max[Length/@Split[#,#2-#==1&]]& – DavidC Oct 11 '14 at 15:28 • @DavidCarraher Sweet! Thanks... I always forget that Split takes a test function. – Martin Ender Oct 11 '14 at 15:30 ## Python new: def s(q): i = r = 1 l = -1 for n in q: if n == l + 1: i += 1 elif i > r: r,i = i,1 else: i=1 l=n return i if i > r else r  old (buggy): def s(q): i=r=1;l=-1 for n in q: if n==l+1:i+=1 elif i>r:r,i=i,1 l=n return r  test case: x = [1,2,3,50,56,58,60,61,90,100] print x print s(x) >>> 3  edit: forgot the input numbers had to be in order. fixed edit2: fixed a problem when all the numbers are a sequence, eg 1,2,3,4,5,6,7,8,9,10, and it returned just '1' edit3: oops, didn't realize it wasn't code golf. • Try using x = [1,2,3,4,5,6,7,8,9,10] the result will be 1. Basically if the very last digit is part of a consecutive group it will return the wrong count. – Bromide Jan 6 '12 at 5:50 • @bromide thanks, fixed now – Blazer Jan 6 '12 at 6:38 • It's not a golf challenge. Please visit this meta thread: meta.codegolf.stackexchange.com/q/456/373 – user unknown Jan 10 '12 at 7:09 • okay thanks, didn't realize – Blazer Jan 11 '12 at 6:59 ## Scheme/Racket Here's a trivial answer in Scheme... (define f (λ (l) (letrec ((g (λ (l M c p) (cond ((null? l) (max M c)) ((= (car l) (+ p 1)) (g (cdr l) M (+ c 1) (car l))) (else (g (cdr l) (max M c) 1 (car l))))))) (g l 1 1 -2)))) (f '(1 2 33 44 55 66 77 88 98)) ;=> 2 (f '(1 3 23 24 30 48 49 70 80)) ;=> 2 (f '(6 9 50 51 52 72 81 83 92)) ;=> 3  where • l is the list • M is the Maximum consecutive number count found so far • c is the current consecutive number count • p is the previous number in the list ## JavaScript (80 93107) for(n=prompt(c=m=1).split(' '),i=9;i;m=++c>m?c:m)c*=!(--n[i]-n[--i])|0;alert(m);  Edit 1: Replaced a with n[i] and b with n[i-1]. Converted Math.max to ternary if. Moved initialization statement into for(. Edit 2: Reversed iteration direction to eliminate need for i++ by changing to --i in second n[--i]. Replaced i++ with part of if body. Changed condition to i to take advantage of ending at 0 = false. Hard-code starting value of 9 due to spec 10 random numbers. ## Python, 87 characters Recursive solution: def s(l): n=1 while n<len(l)and l[n]-l==n:n+=1 return max(n,s(l[n:])if l else 0)  Testing: >>> s([1, 2, 33, 44, 55, 66, 77, 88, 98]) 2 >>> s([1, 3, 23, 24, 30, 48, 49, 70, 80]) 2 >>> s([6, 9, 50, 51, 52, 72, 81, 83, 92]) 3  Since I can't edit code, I'll redefine the Scheme answer (Racket or not, portable and easier to read). Variables have descriptive names and there is only one recursion of the list while being error free (i think). Who cares about characters when you got efficiency? (define (count-consecutive lst) (call-with-current-continuation (lambda (return) (define (test n) (unless (integer? n) (return (error "Not integer: " n)))) (define (g best) (f best n (cdr lst))) (let ([prev (car lst)] [count 0]) (test prev) (let f ([best 0] [prev prev] [lst (cdr lst)]) (if (null? lst) best (let ([n (car lst)]) (test n) (if (= (- n prev) 1) (let ([count (+ count 1)]) (if (> count best) (g count) (g best))) (let ([count 0]) (g best))))))))))  ## Scala def maxconsec(ln:List[Int]):Int= { var (max,current,last)=(1,1,-1) for(n<-ln) { if(n==last+1) { current+=1; if(current>max)max=current } else { current=1 } last=n } return max }  I think this is O(n); is it possible to be more efficient? Can the OP elaborate on how efficiency is being measured here? Usage: (you can test it on simplyscala.com) maxconsec(List(6,9,50,51,52,72,81,83,90,92))  ## Python def s(n): l=0 t=1 for i in range(0,9): if n[i]+1==n[i+1]: t+=1 else: if l<t: l=t t=1 return l  # Ruby I'm generally not that great at knowing more efficient methods. Might be some ruby standard lib things I'm missing. def consec_count(arr) tg = 1 cg = 1 l = arr arr.each do |v| if l + 1 == v cg += 1 tg = cg if tg < cg else cg = 1 end l = v end tg end  # R, 34 bytes u=rle(1:99%in%scan());max(u$l*u$v)  Try it online! This is a copy-paste of Micky T's answer to this challenge. Upvote him! # 05AB1E, 7 6 bytes ∞-γ€gZ  Try it online! Thanks to @Kevin Cruijssen for -1 byte Code: ∞ push endless list [1, 2, 3, 4, 5, ...] - subtract that from input γ group by equal elements €g push lengths of each group Z push max length implicitly print top of stack  • 6 bytes (∞ instead of TL). PS: M is the max number on the entire stack, whereas à and Z are the max number in the list (where à pops the list itself; and Z does not pop the list). – Kevin Cruijssen Sep 30 '19 at 9:35 ## Java public static int getConsecutiveCount(int[] A) { int r = 1, t = 1; boolean c = false; for (int i = 0; i < A.length; i++) { if (i + 1 < A.length) { if (A[i + 1] - A[i] == 1) { t++; c = true; } else { c = false; } } else { c = false; } if (t > r && !c) { r = t; t = 1; } } return r; }  ## Just for fun, CJam, 24 bytes l~]M\{:H(=+H}*;0a/:,$W=)


I know this is not valid as the language did not exist at the time of asking the question, but I thought I will give it a try.

How it works:

l~]M\                     "Read the input, convert to array, put an empty array M before it";
{      }*            "For each pair of the array, run the code block";
:H(                 "Assign the second number from the pair to H and decrement it";
=+               "Check if it is equal to previous number and put result in M";
H              "Put back the second number so as to be used in next iteration":
;0a         "Drop the trailing last number and put  on stack";
/        "Split M on ";
:,      "For each split element, replace it with its length";
$W= "Sort the final array and take its last element"; ) "Increment this highest element from the array";  Try it online here # Perl my @o = (1,4,4,6,7,45,46,47,48,98); sub r{$c=1;
$l=pop@_;$m=1;
while($n=pop@_){ if($l-$n==1){++$c;$m=$c if $c>$m}
else{$c=1}$l=$n }$m
}

print "MAX: " . r(@o);


Output: MAX: 4

# Japt, 9 bytes

äa è_¥1ÃÄ


Try it online!

• è¥1  saves a byte. However, this approach will fail if the input contains more than 1 run of consecutive numbers. – Shaggy Sep 30 '19 at 12:25

# Julia 0.6, 55 bytes

a->((d=diff(a))[d.!=1]=x=0;maximum(x=(x+y)y for y=d)+1)


Try it online!

Going for $O(n)$,

### 82 bytes

a->(l=m=0;i=1;while i<length(a);a[i]==a[i+1]-1 ? l+=1 : l=1;l>m&&(m=l);i+=1;end;m)


Try it online!

which ungolfed is:

function f(a)
l = m = 0
i = 1
while i < length(a)
a[i] == a[i+1]-1 ? l+=1 : l=1
if l > m
m = l
end
i += 1
end
return m
end


# Japt-h, 9 bytes

í- ò¦ mÊn


Try it

# Python 3, 73 bytes

def f(l):s=[n-i for i,n in enumerate(l)];return max(s.count(i)for i in s)


Try it online!

This works by subtracting the index from each number in the list and finding the greatest frequency in the list.