查找最大序列长度


29

假设我们有一个字符串,并且我们想要找到每个字母的最大重复序列。

例如,给定样本输入:

"acbaabbbaaaaacc"

样本输入的输出可以是:

a=5
c=2
b=3

规则:

  • 您的代码可以是函数或程序-供您选择
  • 输入可以通过标准输入,文件或函数参数
  • 输出应仅包含出现在输入中的字符
  • 输入最大长度为1024
  • 输出顺序无关紧要,但必须以[char] = [最大重复序列] [定界符]的形式打印
  • 字符串可以包含任何字符

比赛于世界标准时间23:59星期四结束。


输入字符串的长度是否有最大值?
sigma 2014年

2
输出是否必须完全与给定一致?可以为未出现的字母说0吗?直到最高字母的每个字母都会出现至少一次?
xnor 2014年

1
请说明是否必须完全按照您的问题中的说明格式化输出。当前的16个答案中,至少有10个使用不同的格式,另外三个则表示两个不同的版本。
丹尼斯2014年

1
@乔伊你可能应该打高尔夫。通过您的宽恕,我将最终看到l:S_&{'=L{2$+_S\#)}g,(N}/生产系统!我会骂你的名字。
Cruncher 2014年

Answers:


22

8086机器代码,82 80

x.com文件内容:

B7 3D 89 DF B1 80 F3 AA 0D 0A 24 B4 01 CD 21 42
38 D8 74 F7 38 17 77 02 88 17 88 C3 31 D2 3C 0D
75 E9 BF 21 3D B1 5E 31 C0 F3 AE E3 EE 4F BB 04
01 8A 05 D4 0A 86 E0 0D 30 30 89 47 02 3C 30 77
04 88 67 03 43 89 3F 89 DA B4 09 CD 21 47 EB D7

它仅支持最多99个字符的重复。

源代码(用作debug.com汇编程序的输入),带注释!

a
    mov bh, 3d         ; storage of 128 bytes at address 3d00
    mov di, bx
    mov cl, 80
    rep stosb          ; zero the array
    db 0d 0a 24
; 10b
    mov ah, 1
    int 21             ; input a char
    inc dx             ; calculate the run length
    cmp al, bl         ; is it a repeated character?
    je  10b
    cmp [bx], dl       ; is the new run length greater than previous?
    ja  11a
    mov [bx], dl       ; store the new run length
; 11a
    mov bl, al         ; remember current repeating character
    xor dx, dx         ; initialize run length to 0
    cmp al, d          ; end of input?
    jne 10b            ; no - repeat
    mov di, 3d21       ; start printing run lengths with char 21
    mov cl, 5e         ; num of iterations = num of printable characters
; 127
    xor ax, ax
    repe scasb         ; look for a nonzero run length
    jcxz 11b           ; no nonzero length - exit
    dec di
    mov bx, 104        ; address of output string
    mov al, [di]       ; read the run length
    aam                ; convert to decimal
    xchg al, ah
    or  ax, 3030
    mov [bx+2], ax
    cmp al, 30         ; was it less than 10?
    ja  145
    mov [bx+3], ah     ; output only one digit
    inc bx             ; adjust for shorter string
; 145
    mov [bx], di       ; store "x=" into output string
    mov dx, bx         ; print it
    mov ah, 9
    int 21
    inc di
    jmp 127            ; repeat
; 150

rcx 50
n my.com
w
q

以下是一些我认为很有趣的高尔夫技巧:

  • 数组的地址是 3d00,其中3d的ASCII码在哪里=。通过这种方式,地址为字符数组的入口x3d78。当解释为2个字符的字符串时,为x=
  • 输出缓冲区在地址104; 它会覆盖不再需要的初始化代码。行尾序列0D 0A 24作为无害代码执行。
  • aam这里的说明不提供任何打高尔夫球的信息,尽管可以...
  • 将数字写两次,首先假定它大于10,然后更正它是否较小。
  • 出口指令的地址晦涩难懂11bC3运气好的话,其中包含了所需的机器代码。

有趣的方法。但是,由于限制了99次重复,因此无法处理提供了1024个aaaa输入的情况。
Homer6

14

CJam,27 26 25字节

l:S_&{'=L{2$+_S\#)}g,(N}/

在线尝试。

$ cjam maxseq.cjam <<< "acbaabbbaaaaacc"
a=5
c=2
b=3

怎么运行的

l:S       " Read one line from STDIN and store the result in “S”.                   ";
_&        " Intersect the string with itself to remove duplicate characters.        ";
{         " For each unique character “C” in “S”:                                   ";
  '=L     " Push '=' and ''.                                                        ";
  {       "                                                                         ";
    2$+_  " Append “C” and duplicate.                                               ";
    S\#)  " Get the index of the modified string in “S” and increment it.           ";
  }g      " If the result is positive, there is a match; repeat the loop.           ";
  ,       " Retrieve the length of the string.                                      ";
  (       " Decrement to obtain the highest value that did result in a match.       ";
  N       " Push a linefeed.                                                        ";
}/        "                                                                         ";

9

J-52个字节

好了,再次简单的方法。

f=:([,'=',m=:":@<:@#@[`(]m~[,{.@[)@.(+./@E.))"0 1~~.

说明:

f=:([,'=',m=:":@<:@#@[`(]m~[,{.@[)@.(+./@E.))"0 1~~.
                                                 ~~. Create a set of the input and apply it as the left argument to the following.
   ([,'=',m=:":@<:@#@[`(]m~[,{.@[)@.(+./@E.))"0 1    The function that does the work
                                             "0 1    Apply every element from the left argument (letters) with the whole right argument (text).
                                  @.(+./@E.)         Check if the left string is in right string.
                       (]m~[,{.@[)                   If yes, add one letter to the left string and recurse.
             ":@<:@#@[                               If not, return (length of the left string - 1), stringified.
    [,'=',                                           Append it to the letter + '='

例:

   f 'acbaabbbaaaaacc'
a=5
c=2
b=3
   f 'aaaabaa'
a=4
b=1

如果允许自由格式的输出(与其他许多答案一样),我也有一个45字节的版本。这些框代表一个框列表(是的,它们的打印方式是这样的,尽管SE的行高将它们打断了)。

   f=:([;m=:<:@#@[`(]m~[,{.@[)@.(+./@E.))"0 1~~.
   f 'acbaabbbaaaaacc'
┌─┬─┐
│a│5│
├─┼─┤
│c│2│
├─┼─┤
│b│3│
└─┴─┘
   f 'aaaabaabba'
┌─┬─┐
│a│4│
├─┼─┤
│b│2│
└─┴─┘

8

Ruby,72岁

(a=$*[0]).chars.uniq.map{|b|puts [b,a.scan(/#{b}+/).map(&:size).max]*?=}

这将从命令行参数中获取输入,然后输出至stdout。


chars比短split("")
Ventero 2014年

@Ventero我尝试过,但是chars提供了一个枚举器而不是数组。我在1.9.3,所以是2.0吗?
2014年

是的,在2.0中chars返回一个数组。
Ventero 2014年

它可能会延伸一些规则,但也许使用p代替puts
Shelvacu 2014年

1
我懂了。尽管这样不太美观,但我看不到它会违反任何规则。
daniero 2014年

7

GolfScript,26个字节

:s.&{61{2$=}s%1,/$-1=,n+}%

在线尝试。

说明:

  • :s将输入字符串保存在变量中,s以备后用。
  • .&提取输入中的唯一字符,{ }%然后循环中的其余代码对其进行迭代。
  • 61 将数字61(等号的ASCII码)压入堆栈中当前字符的顶部,以用作输出定界符。
  • {2$=}s%接受字符串s,如果其字符等于要迭代的当前字符,则将其字符替换为1;否则将其替换为0。(它还将当前字符留在堆栈上以进行输出。)
  • 1,/ 接受这个由一和零组成的字符串,并将其拆分为零。
  • $对结果子串进行排序,-1=提取最后一个子串(由于它们都由相同字符的重复组成,因此最长),然后,返回该子串的长度。
  • n+ 字符串化长度,并在其后添加换行符。

附言 如果输出中的等号是可选的,则61可以省略(用2$代替1$),总长度为24个字节

:s.&{{1$=}s%1,/$-1=,n+}%

1
如果您按下第61一个按钮,则可以保存交换:s.&{61{2$=}s%1,/$-1=,n+}%
2014年

@霍华德:谢谢!
Ilmari Karonen 2014年

6

CoffeeScript,109个字节

我喜欢正则表达式。

f=(s)->a={};a[t[0]]=t.length for t in s.match(/((.)\2*)(?!.*\1)/g).reverse();(k+'='+v for k,v of a).join '\n'

这是您可以在浏览器控制台中尝试的已编译JavaScript

f = function(s) {
  var a, t, _i, _len, _ref;
  a = {};
  _ref = s.match(/((.)\2*)(?!.*\1)/g).reverse();
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    t = _ref[_i];
    a[t[0]] = t.length;
  }
  return a;
};

那你可以打电话

f("acbaabbbaaaaacc")

要得到

c=2
a=5
b=3

这似乎为的输入生成了错误的结果aaaabaa
Ventero 2014年

@Ventero你是对的,有两个问题。一个很容易解决,但我需要考虑另一个。
Martin Ender 2014年

@Ventero固定。
Martin Ender 2014年

5

Pyth,24 25 26(或29)

=ZwFY{Z=bkW'bZ~bY)p(Yltb

测试可以在这里完成:链接

输出格式为:

('a', 5)
('c', 2)
('b', 3)

说明:

=Zw              Store one line of stdin in Z
FY{Z             For Y in set(Z):
=bk              b=''
W'bZ             while b in Z:
~bY              b+=Y
)                end while
p(Yltb           print (Y, len(b)-1)

蟒蛇:

k=""
Z=copy(input())
for Y in set(Z):
 b=copy(k)
 while (b in Z):
  b+=Y
 print(_tuple(Y,len(tail(b))))

为了获得正确的(a = 5)输出,请使用:

=ZwFY{Z=bkW'bZ~bY)p++Y"="`ltb

29个字符


似乎您有完全相同的想法。为此+1。
seequ 2014年

@TheRare是的,这似乎是一种非常好的方法。
isaacg 2014年

与您的算法没有真正的关系,但是python的输出令人困惑,因为它k=''是在其他地方定义的。
gggg 2014年

是的,对此感到抱歉。我会努力改善它。我也会编辑它。
isaacg 2014年

5

C,126个 125 119字节

l,n,c[256];main(p){while(~(p=getchar()))n*=p==l,c[l=p]=c[p]>++n?c[p]:n;for(l=256;--l;)c[l]&&printf("%c=%d\n",l,c[l]);}

运行:

$ gcc seq.c 2>& /dev/null
$ echo -n 'acbaabbbaaaaacc' | ./a.out
c=2
b=3
a=5

您可以在此答案中替换getchar()>0~getchar()
anatolyg 2014年

@anatolyg EOF是否保证正好为-1?我认为它只是专门定义为<0。
蓬松的

我认为-1很常见(例如Windows和Linux),因此您可以将其用于Code Golf。对于生产代码,less than zero完全可以,但是== EOF更清楚。
anatolyg 2014年

@anatolyg当然,实际上我每规范EOF显然甚至不保证为<0猜测-它可能还可以,例如,256所以我就保存单字节。:)
蓬松的

2
EOF确保为负数,并且即使char已签名也使用-1 ;看到这里
anatolyg

4

Mathematica74 72 69

Print[#[[1,1]],"=",Max[Tr/@(#^0)]]&/@Split@Characters@#~GatherBy~Max&

% @ "acbaabbbaaaaacc"
a=5
c=2
b=3

不是很好,但是字符串不是Mathematica的最佳区域。越来越好了。:-)


This is pretty impressive golfing (saying this after having tried it myself ...)
Szabolcs

v10, not a full solution: First@*MaximalBy[Length] /@ GroupBy[First]@Split@Characters[#] & At least it's pretty straightforward and readable.
Szabolcs

@Szabolcs Thanks! What's the difference between GroupBy and GatherBy?
Mr.Wizard

The main difference is that GroupBy returns an Association. I haven't studied the other differences in detail yet. reference.wolfram.com/language/ref/GroupBy.html You can try it in the cloud with a free account (that's how I'm playing with these).
Szabolcs

3

C# (LinQPad)

146

This is tsavino's answer but shorter. Here, I used Distinct() instead of GroupBy(c=>c). Also the curly braces from the foreach-loop are left out:

void v(string i){foreach(var c in i.Distinct())Console.WriteLine(c+"="+(from Match m in Regex.Matches(i,"["+c+"]+")select m.Value.Length).Max());}

136

I tried using a lambda expression instead of the normal query syntax but since I needed a Cast<Match> first, the code became 1 character longer... Anyhow, since it can be executed in LinQPad, you can use Dump() instead of Console.WriteLine():

void v(string i){foreach(var c in i.Distinct())(c+"="+(from Match m in Regex.Matches(i,"["+c+"]+")select m.Value.Length).Max()).Dump();}

Further study of the code got me thinking about the Max(). This function also accepts a Func. This way I could skip the Select part when using the lambda epxression:

void v(string i){foreach(var c in i.Distinct())(c+"="+Regex.Matches(i,"["+c+"]+").Cast<Match>().Max(m=>m.Value.Length)).Dump();}

Thus, final result:

128

Update:

Thanks to the tip from Dan Puzey, I was able to save another 6 characters:

void v(string i){i.Distinct().Select(c=>c+"="+Regex.Matches(i,"["+c+"]+").Cast<Match>().Max(m=>m‌​.Value.Length)).Dump();}

Length:

122


Thank you for your improvements, I didn't know about the trick with the .Dump() in LinqPad. To be honest, I developed the code in Visual Studio and copied it to LinqPad to save some characters because LinqPad doesn't need a main method.
tsavinho

Thanks! I also just got to know the Dump() method recently, saves you 10+ chars every time :) The curly braces was easy and the rest was a bit of braincracking :D
Abbas

1
If you're happy to use LinqPad's IEnumerable display style you can save another 8 chars, with this as your body: i.Distinct().Select(c=>c+"="+Regex.Matches(i,"["+c+"]+").Cast<Match>().Max(m=>m.Value.Length)).Dump();
Dan Puzey

3

Python 3 (70)

s=input()
for c in set(s):
 i=1
 while c*i in s:i+=1
 print(c,'=',i-1)

Even golfed Python can be very readable. I think this code is fully idiomatic except for single-letter variables and a one-line while loop.

Example runs:

>>> helloworld
e = 1
d = 1
h = 1
l = 2
o = 1
r = 1
w = 1
>>> acbaabbbaaaaacc
a = 5
c = 2
b = 3

This is an interesting solution
Cruncher

1
if you change set(s) to just s I think it still meets the requirements. Nowhere does it say each char must be printed only once.
Cruncher

@Cruncher I agree the OP doesn't specify each letter once, but the other Python answers seem to assume it, so I'll stick with that to be comparable. Though output formats are still inconsistent. I do wish the OP had responded to the requests to clarify.
xnor

2

Ruby, 58

h={}
gets.scan(/(.)\1*/){h[$1]=[h[$1]||0,$&.size].max}
p h

Takes input from STDIN, outputs it to STDOUT in the form {"a"=>5, "c"=>2, "b"=>3}


2

C# in LINQPad - 159 Bytes

Well, at least I beat T-SQL ;P Won't beat anyone else, but I thought I'd share it anyway.

void v(string i){foreach(var c in i.GroupBy(c=>c)){Console.WriteLine(c.Key+"="+(from Match m in Regex.Matches(i,"["+c.Key+"]+")select m.Value.Length).Max());}}

Usage:

v("acbaabbbaaaaacc");

Suggestions are always welcome!


Great answer! I've got some suggestions but that was too long for a comment so click here for my answer. :)
Abbas

2

Powershell 80 77 72

$x=$args;[char[]]"$x"|sort -u|%{"$_="+($x-split"[^$_]"|sort)[-1].length}

You need to run it on console...


1
$x is superfluous. You're three byte shorter not using it. Also sort -u suffices. There is rarely a need of spelling out the complete parameter names. This will, however, fail for certain characters due to the unescaped use in the regex. Depending on how »The string can contain any character« is to be understood, this could be a problem.
Joey

@Joey thanks for the tip on sort -u, however regarding the $x I couldn't get it to work like [char[]]"$args"|sort -u|%{"$_="+($args-split"[^$_]"|sort)[-1].length}, it seems the second $args comes empty... – darkajax 17 mins ago
DarkAjax

Eep, yes. Sorry. That's because it's in a script block, which has its own arguments (the $args there is no longer the one of the script).
Joey

2

Perl - 65 71 76 characters

My first code golf!

For each answer, copy to golf.pl and run as:

echo acbaabbbaaaaacc | perl golf.pl

My shortest solution prints each character as many times as it appears, since that is not prohibited by the rules.

$_=$i=<>;for(/./g){$l=length((sort$i=~/$_*/g)[-1]);print"$_=$l
"}

My next-shortest solution (85 90 characters) only prints each character once:

<>=~s/((.)\2*)(?{$l=length$1;$h{$2}=$l if$l>$h{$2}})//rg;print"$_=$h{$_}
"for keys %h

1

F# - 106

let f s=
 let m=ref(Map.ofList[for c in 'a'..'z'->c,0])
 String.iter(fun c->m:=(!m).Add(c,(!m).[c]+1))s;m

In FSI, calling

f "acbaabbbaaaaacc"

gives

val it : Map<char,int> ref =
  {contents =
    map
      [('a', 8); ('b', 4); ('c', 3); ('d', 0); ('e', 0); ('f', 0); ('g', 0);
       ('h', 0); ('i', 0); ...];}

However, to print it without the extra information, call it like this:

f "acbaabbbaaaaacc" |> (!) |> Map.filter (fun _ n -> n > 0)

which gives

val it : Map<char,int> = map [('a', 8); ('b', 4); ('c', 3)]

1

Javascript, 116 bytes

y=x=prompt();while(y)r=RegExp(y[0]+'+','g'),alert(y[0]+'='+x.match(r).sort().reverse()[0].length),y=y.replace(r,'')

Sample output:

lollolllollollllollolllooollo
l=4
o=3

acbaabbbaaaaacc
a=5
c=2
b=3

helloworld
h=1
e=1
l=2
o=1
w=1
r=1
d=1 

1

T-SQL (2012) 189 171

Edit: removed ORDER BY because rules allow any output order.

Takes input from a CHAR variable, @a, and uses a recursive CTE to create a row for each character in the string and figures out sequential occurrences.

After that, it's a simple SELECT and GROUP BY with consideration for the order of the output.

Try it out on SQL Fiddle.

WITH x AS(
    SELECT @a i,''c,''d,0r,1n
    UNION ALL 
    SELECT i,SUBSTRING(i,n,1),c,IIF(d=c,r+1,1),n+1
    FROM x
    WHERE n<LEN(i)+2
)
SELECT d+'='+LTRIM(MAX(r))
FROM x
WHERE n>2
GROUP BY d

Assigning the variable:

DECLARE @a CHAR(99) = 'acbaabbbaaaaacc';

Sample output:

a=5
c=2
b=3

I don't think I've seen a SQL solution here before. Interesting.
Seiyria

consider the str, function instead of ltrim. You can also name your variable @ to save a char. This allows you to lose the i variable in the rcte. I think you can shave quite a few chars that way. You might also be able to rewrite the query with using a windowing function like sum over rows preceding or lag. I haven't quite formed how yet mind you.
Michael B

@MichaelB thanks for the advice. The trouble I have with str() is that it outputs a bunch of extra spaces. I will definitely start using @ as a variable!
comfortablydrei

It's true that str always outputs 10 characters, but this is golfing :P
Michael B

1

Haskell - 113 120 bytes

import Data.List
main=interact$show.map(\s@(c:_)->(c,length s)).sort.nubBy(\(a:_)(b:_)->a==b).reverse.sort.group

Tested with

$ printf "acbaabbbaaaaacc" | ./sl
[('a',5),('b',3),('c',2)]

You can use the . (compose) function to avoid creating a lambda where the parameter only appears after the end of a chain of $ connected functions. To do this, simply change all the $s to .s (example: (\i->reverse$sort$group i) turns into reverse.sort.group.
YawarRaza7349

1

JavaScript [83 bytes]

prompt().match(/(.)\1*/g).sort().reduce(function(a,b){return a[b[0]]=b.length,a},{})

Run this code in the browser console.

For input "acbaabbbaaaaacc" the console should output "Object {a: 5, b: 3, c: 2}".


1

JavaScript - 91

for(i=0,s=(t=prompt()).match(/(.)\1*/g);c=s[i++];)t.match(c+c[0])||alert(c[0]+'='+c.length)

EDIT: My first solution obeys the rules, but it prints several times single char occurrences like abab => a=1,b=1,a=1,b=1 so I came out with this (101 chars), for those not satisfied with my first one:

for(i=0,s=(t=prompt()).match(/((.)\2*)(?!.*\1)/g);c=s[i++];)t.match(c+c[0])||alert(c[0]+'='+c.length)

0

Julia, 85

f(s)=(l=0;n=1;a=Dict();[c==l?n+=1:(n>get(a,l,1)&&(a[l]=n);n=1;l=c) for c in s*" "];a)
julia> f("acbaabbbaaaaacc")
{'a'=>5,'c'=>2,'b'=>3}

0

Python3 - 111, 126, 115 114 111 bytes

Executable code that will read 1 line (only use lowercase letters a-z)

d={}.fromkeys(map(chr,range(97,123)),0)
for c in input():d[c]+=1
[print("%s=%d"%(p,d[p]))for p in d if d[p]>0]

Edit: Excluded unnecessary output on request from @Therare

The output looks nice

~/codegolf $ python3 maxseq.py 
helloworld
l=3
o=2
h=1
e=1
d=1
w=1
r=1

You really should exclude the unnecessary output. (I think)
seequ

"fixed" the output
Dog eat cat world

You can remove spaces between braces, numbers and keywords, such as for or if.
seequ

3
I think you've misread the questions. l=2 and o=1 for "helloworld"
gnibbler

4
You're counting total appearances instead of maximum consecutive appearances.
xnor

0

JavaScript - 141 137 125

I don't like regex :)

function g(a){i=o=[],a=a.split('');for(s=1;i<a.length;){l=a[i++];if(b=l==a[i])s++;if(!b|!i){o[l]=o[l]>s?o[l]:s;s=1}}return o}

Run

console.log(g("acbaabbbaaaaacc"));

outputs

[ c: 2, a: 5, b: 3 ]

0

Javascript, 109 104 100 98 bytes

function c(s){q=l={};s.split('').map(function(k){q[k]=Math.max(n=k==l?n+1:1,q[l=k]|0)});return q}

Example usage:

console.log(c("aaaaaddfffabbbbdb"))

outputs:

{ a: 5, d: 2, f: 3, b: 4 }

0

PHP, 104 102 96

<?php function _($s){while($n=$s[$i++]){$a[$n]=max($a[$n],$n!=$s[$i-2]?$v=1:++$v);}print_r($a);}

usage

_('asdaaaadddscc');

printed

Array ( [a] => 4 [s] => 1 [d] => 3 [c] => 2 )

0

Java 247

import java.util.*;public class a{public static void main(String[]a){Map<Character, Integer> m = new HashMap<>();for(char c:a[0].toCharArray()){Integer v=m.get(c);m.put(c,v==null?1:v+1);}for(char c:m.keySet())System.out.println(c+"="+m.get(c));}}

Does import java.util.*; work in Java?
seequ

yes and i paste old code
user902383

The OP said it could just be a function/method so you can shorten this to simply the method.
Rudi Kershaw

This outputs all occurrences of the character in the String, not the longest substrings consisting of the character. For example, acbaabbbaaaaacc outputs a=8; b=4; c=3 instead of a=5; b=3; c=2.
Kevin Cruijssen

0

C 169

Iterates each printable character in ASCII table and counts max from input string.

#define N 128
int c,i,n;
char Y[N],*p;
int main(){gets(Y);
for(c=33;c<127;c++){p=Y;n=0,i=0;while(*p){if(*p==c){i++;}else{n=(i>n)?i:n;i=0;}p++;}
if(n>0) printf("%c=%d\n",c,n);}
}

Have you tested this? It doesn't look like it produces correct output on a lot of strings , and also doesn't meet the spec which says that input can be up to 1024 long... plus, there's a lot of easy golfing techniques that you've missed. :)
fluffy

0

JavaScript 116

prompt(x={}).replace(/(.)\1*/g,function(m,l){n=m.length
if(!x[l]||x[l]<n)x[l]=n})
for(k in x)console.log(k+'='+x[k])

0

Groovy - 80 chars

Based on this clever answer by xnor :

t=args[0];t.toSet().each{i=0;
while(t.contains(it*++i));
println "${it}=${i-1}"}

Output:

$ groovy Golf.groovy abbcccdddd
d=4
b=2
c=3
a=1

Ungolfed:

t=args[0]

t.toSet().each { c ->
    i=0
    s=c

    // repeat the char c with length i
    // e.g. "b", "bb", "bbb", etc
    // stop when we find a length that is not in t:
    // this is the max + 1
    while (t.contains(s)) {
        i++
        s=c*i
    }
    println "${c}=${i-1}"
}

Does that actually count the maximum sequence length? I don't see how that would work correctly for a string like "aabbbbaaaabbbbbba" although I don't know Groovy either.
fluffy

It works for your example. I've updated the ungolfed version. Note that "a" * 4 == "aaaa" .
Michael Easter

Ah, I see how it works now. Clever.
fluffy
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.