| Bytes | Lang | Time | Link |
|---|---|---|---|
| 073 | R | 240623T130416Z | int 21h |
| 017 | 05AB1E | 170529T130629Z | kalsower |
| 069 | Python 3 | 140625T225716Z | xnor |
| 040 | Bash / GNU core utils | 210227T194429Z | xhienne |
| 012 | Jelly | 210227T011227Z | caird co |
| 016 | Husk | 210227T160326Z | Dominic |
| 018 | Husk | 210227T140037Z | Razetime |
| 192 | Java | 210227T044829Z | Unmitiga |
| 041 | APL Dyalog | 170529T124944Z | Adá |
| 107 | Clojure | 170111T201223Z | NikoNyrh |
| 088 | Python 3 | 140625T194336Z | jermenko |
| 041 | BACCHUS | 140630T192436Z | Averroes |
| nan | Perl 65 | 140627T170644Z | KJP |
| 045 | J | 140629T182304Z | jpjacobs |
| 105 | Clojure | 140629T113050Z | seequ |
| 097 | Scala – 99 as program | 140628T214200Z | Karol S |
| nan | It's written in Python | 140628T135524Z | Crane |
| 072 | Powershell | 140626T231725Z | DarkAjax |
| 091 | JavaScript | 140626T162430Z | core1024 |
| 163 | R | 140626T134219Z | djhurio |
| 103 | Javascript | 140627T144943Z | edc65 |
| nan | 140627T123845Z | Abbas | |
| 080 | Groovy | 140627T033614Z | Michael |
| 083 | JavaScript [83 bytes] | 140627T104048Z | VisioN |
| nan | 140625T225355Z | gxtaillo | |
| 080 | 8086 machine code | 140626T081306Z | anatolyg |
| 119 | C | 140626T052238Z | fluffy |
| 116 | JavaScript | 140626T201653Z | wolfhamm |
| 169 | C | 140626T193114Z | bacchusb |
| 171 | TSQL 2012 | 140625T224209Z | comforta |
| 109 | CoffeeScript | 140625T184339Z | Martin E |
| nan | 140626T162041Z | Ramasamy | |
| 247 | Java | 140626T132750Z | user9023 |
| 159 | C# in LINQPad 159 Bytes | 140626T132629Z | tsavinho |
| 025 | CJam | 140625T201137Z | Dennis |
| 026 | GolfScript | 140625T235515Z | Ilmari K |
| 055 | Python 62 | 140626T104706Z | Mardoxx |
| 2429 | Pyth | 140625T211947Z | isaacg |
| nan | 140626T084711Z | lastbyte | |
| 116 | Javascript | 140626T091612Z | Дамян Ст |
| 098 | Javascript | 140626T062418Z | fluffy |
| 069 | Mathematica | 140626T030239Z | Mr.Wizar |
| 125 | JavaScript | 140625T225109Z | Matt |
| 052 | J | 140625T200753Z | seequ |
| nan | Python3 111 | 140625T200839Z | Dog eat |
| 085 | Julia | 140625T202339Z | gggg |
| 072 | Ruby | 140625T183411Z | afuous |
| 058 | Ruby | 140625T201019Z | histocra |
| 106 | F# | 140625T192943Z | Jwosty |
R, 73 bytes
paste(names(b<-by((r<-rle(el(strsplit(scan(,""),""))))$l,r$v,max)),"=",b)
I would like to mention that this solution uses rle function, which was introduced in the R version 3.6.2 (Dec. 2019); therefore my answer and the earlier one from 2014 are not directly comparable.
05AB1E, 17 bytes
ÙvIγʒyå}€gZy…ÿ=ÿ,
ÙvIγʒyå}€gZy…ÿ=ÿ, Argument s
Ùv For each c in s uniquified
Iγ Split s into chunks of consecutive equal elements
ʒyå} Filter: Keep elements that contain c
€g Map to element length
Z Get max
y…ÿ=ÿ, Print "c=max"
Python 3, 69 bytes
s=input()
for c in set(s):
i=0
while-~i*c in s:i+=1
print(c,'=',i)
Even golfed Python can be very readable. I think this code is fully idiomatic except for the -~i for i+1 and the single-letter variables. Thanks to pxeger for saving 1 byte.
Example runs:
>>> helloworld
e = 1
d = 1
h = 1
l = 2
o = 1
r = 1
w = 1
>>> acbaabbbaaaaacc
a = 5
c = 2
b = 3
Bash / GNU core utils (40)
fold -1|uniq -c|sort -k2 -k1r|uniq -f1
Output when input is "acbaabbbaaaaacc":
5 a
3 b
2 c
Explanation:
fold -1adds a newline after each characteruniq -ccounts the number of consecutive identical linessort -k2 -k1rsorts the result so as the maximum count for each character comes firstuniq -f1keeps only the first line for each character
Jelly, 12 bytes
ŒriƇṀj”=ʋⱮQY
-2 bytes thanks to Unrelated String!
8 bytes to output as a list of pairs
How it works
ŒriƇṀj”=ʋⱮQY - Main link. Takes a string S on the left
ʋ - Group the previous 4 links into a dyad f(S, C):
Œr - Run-length encode S
Ƈ - For each sublist in rle(S), keep it if:
i - It contains C
Ṁ - Maximum
As all elements are in the form [C, n] for integers n,
Python considers the maximum as the greatest n
j”= - Join with "="; Yields [C, "=", n]
Q - Get the unique characters of S
Ɱ - For each unique character C in S, yield f(C, S)
Y - Join by newlines and output
Husk, 16 bytes
mS:(:'=s▲`mg¹#)U
Explanation:
m U # for each of the unique elements of the input
S: # prepend the element to
(:'= ) # '=' prepended to
▲ # the maximum of
# # the number of times it occurs in
`mg¹ # each group of identical items in the input,
s # converted into a string
I saw that Razetime had answered this in Husk, so I had to have a go too...
Husk, 18 bytes
mȯJ'=§eo;←osL►Lk←g
11 bytes if we ignore the exact input format and display as a list of pairs instead.
Java, 192 bytes
import java.util.*;s->{int p=0,c=0;Map<Character,Integer>m=new HashMap();for(byte b:s.getBytes()){c=p==b?c+1:1;m.merge((char)(p=b),c,Math::max);}m.forEach((k,v)->System.out.println(k+"="+v));}
Java, 251 bytes (with regular expressions)
import java.util.regex.*;import java.util.function.*;s->{Matcher m=Pattern.compile("(.)\\1*").matcher(s);Map<String,Integer>a=new HashMap();while(m.find())a.merge(m.group(1),m.group().length(),Math::max);a.forEach((k,v)->System.out.println(k+'='+v));}
APL (Dyalog), 41 bytes
{(⊃,'=',⍕∘≢)¨l[∪⍳⍨⊃¨l←n[⍒≢¨n←⍵⊂⍨1,2≠/⍵]]}
Ungolfed:
{
n←⍵⊂⍨1,2≠/⍵
l←n[⍒≢¨n]
(⊃,'=',⍕∘≢)¨l[∪⍳⍨⊃¨l]
}
{ anonymous function
2≠/⍵ pair-wise sliding window inequality of the argument
1, prepend a one
⍵⊂⍨ use that to partition the argument
n← store in n
n[…] index n with:
⍒ the descending order of
≢¨ the length of each element in
⍵ argument
l← store in l
l[…] index l with:
∪ the unique of
⍳⍨ the first occurrence of each element of
⊃¨l the first element of each of l
(…)¨ apply the following tacit function on each element
⊃ the first element
, concatenated to
'=' an equal sign
, concatenated to
⍕∘≢ the formatted length
}
Clojure, 107 bytes
#(apply str(for[p(vals(group-by last(partition-by(fn[i]i)%)))](str(ffirst p)\=(apply max(map count p))\,)))
Returns "a=5,c=2,b=3," for the example input. This would have been 89 bytes, returning ([\a 5] [\c 2] [\b 3]):
#(for[p(vals(group-by last(partition-by(fn[i]i)%)))][(ffirst p)(apply max(map count p))])
Python 3, 88 bytes
from re import*;a=input();[(i[0],len(max(i))) for i in(findall(l+"+",a)for l in set(a))]
Outputs in a format of:
[('b', 3), ('c', 2), ('a', 5)]
BACCHUS, 41
'acbaabbbaaaaacc'j:A=·z#:B=($A,$0h:a(·>0.$0,'=',·+)?),$B¨n
I have discounted the actual parameter String.
Explanation
j:A= Transform the String in a block (some sort of array) and stores it in A variable.
·z#:B= Read last value on the stack (the block) and removes al duplicates, storing it in B.
( Open for each
$A,$0h:a counts how many times the current element of the for each is present in A (read as a String) and pushes this value to Stack (this avoid inmediate printing of the value).
( Open if
·>0. is last value is > 0 then
$0,'=',·+ Concatenates current for each element, '=' and last value in stack (that will be printed out)
)? Close if
,$B¨ Close for each indicating the block to loop over (B).
n Indicates that the output must be space separated
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
J 45
~.,.'=',.":@({.@>>.//.$&>)@(<;.2~2&(~:/\),1:)
As a verb. Though for using it , you'd need to assign it to a name, eg:
f=:~.,.'=',.":@({.@>>.//.$&>)@(<;.2~2&(~:/\),1:)
f 'acbaabbbaaaaacc'
a=5
c=2
b=3
Short explanation:
@( 2&(~:/\),1:): find where neighbors are different
<;.2~ : cut in these places
( $&> ) : get the length of the string in the box
({.@>) : get the first letter from the box
(>./)/. : get the maximum for each unique char
~.,.'=',.":@( ) : Output: letter = stringified value
Clojure - 105 bytes
I'm learning Clojure at the moment and what would be a better way to do it than golfing? So, here's my second entry to this challenge.
(def f #(apply str(for[c(distinct %)](str c\=(apply max(map count(re-seq(re-pattern(str c\+))%)))"\n"))))
Examples:
=> (f "acbaabbbaaaaacc")
"a=5\nc=2\nb=3\n"
=> (f "aaaabaa")
"a=4\nb=1\n"
=> (println (f "acbaabbbaaaaacc"))
a=5
c=2
b=3
Scala – 99 as program, 97 as function
Program (reads one line from stdin)
for((k,v)<-"(.)\\1*".r.findAllIn(Console.in.readLine).toSeq.groupBy(_(0)))println(k+"="+v.max.size)
Function:
def f(s:String)=for((k,v)<-"(.)\\1*".r.findAllIn(s).toSeq.groupBy(_(0)))println(k+"="+v.max.size)
It's written in Python, in order to run the code, just call thefunction maxsequence(str). For instance, maxsequence('aaaaaannndmdejlsfnsfsssssnnnnnxxx') or
maxsequence("kdkdkdkdjeeeiwwwnnnmdnnsbjdiiiiiiiiiidndbbcbbccbcvcvdddcjdjdjwwwwwwkkkkxlxllllllll")
def maxsequence(str):
count = 1 # count if the letters are repeat
step = 0 # once the next letter changed, step = count.
countArray = [] # put all the sequence numbers in an array
lettersArray = [] # put all the repeat letters in an array
max = 0
# for calculating the max of the array, it needs two indexes to do that
indexFirst = 0
indexNext = 1
i = 0
while(i<len(str) and i<=(len(str)-2)):
if(str[i]==str[i+1]):
count += 1
step = count
else:
lettersArray.append(str[i])
step = count
countArray.append(step)
count = 1
i += 1
countArray.append(step)
lettersArray.append(str[i])
while(countArray[indexFirst]>=countArray[indexNext] and indexNext<(len(countArray)-1)):
indexNext += 1
if(countArray[indexFirst]<=countArray[indexNext]):
indexFirst = indexNext
max = countArray[indexFirst]
for i in range(len(lettersArray)):
print lettersArray[i],"=",countArray[i]
print "The max sequence is:", max
return max
Powershell 80 77 72
$x=$args;[char[]]"$x"|sort -u|%{"$_="+($x-split"[^$_]"|sort)[-1].length}
You need to run it on console...
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)
R (219, 213, 197, 196, 191, 165, 169, 157, 163 characters)
The data.table version added. There was an error in the previous data.table version.
Golfed data.table version (163)
require(data.table);f=function(x){x=strsplit(x,"")[[1]];data.table(x=x,y=cumsum(c(1,x[-1]!=head(x,-1))))[,.N,list(x,y)][order(-N)][!duplicated(x),paste0(x,"=",N)]}
Ungolfed data.table version
require(data.table)
f <- function(x) {
x <- strsplit(x, "")[[1]]
data.table(a=x, y=cumsum(c(1, x[-1] != head(x, -1))))[
, .N, list(a, y)][order(-N)][!duplicated(a), paste0(a, "=", N)]
}
Golfed data.frame version (174)
f=function(x){x=strsplit(x,"")[[1]];d=data.frame(a=x,y=cumsum(c(1,x[-1]!=head(x,-1))));d=aggregate(d$y,d,length);d=d[order(-d$x),];d=d[!duplicated(d$a),];paste0(d$a,"=",d$x)}
Ungolfed data.frame version
f <- function(x) {
x <- strsplit(x, "")[[1]]
d <- data.frame(a = x, y = cumsum(c(1, x[-1] != head(x, -1))))
d <- aggregate(d$y, d, length)
d <- d[order(-d$x), ]
d <- d[!duplicated(d$a), ]
paste0(d$a, "=", d$x)
}
f("acbaabbbaaaaacc")
f("acbaabbbaaaaaccdee")
Javascript (E6) 103
A javascript solution that cares about the requested output format.
F=a=>(p=q={},m={},[...a].map(x=>(x!=p&&(q[p=x]=0),m[x]>++q[x]?0:m[x]=q[x])),''+[i+'='+m[i]for(i in m)])
Ungolfed
F=a=>(
p=q={}, m={},
[...a].map(
x=>(
x!=p && (q[p=x]=0),
m[x] > ++q[x] ? 0 : m[x] = q[x]
)
),
'' + [i+'='+m[i] for(i in m)]
)
Test
In Firefox console
console.log(F("aaaaaddfffabbbbdb"))
a=5,d=2,f=3,b=4
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
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}"
}
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}".
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)]
8086 machine code, 82 80
Contents of the x.com file:
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
It only supports repetitions of up to 99 characters.
Source code (served as input for the debug.com assembler), with comments!
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
Here are some golfing techniques used here that I think were fun:
- array's address is
3d00, where3dis the ascii-code for=. This way, the address for array's entry for characterxis3d78. When interpreted as a 2-character string, it'sx=. - Output buffer is at address
104; it overwrites initialization code that is no longer needed. End-of-line sequence0D 0A 24is executed as harmless code. - The
aaminstruction here doesn't provide any golfing, though it could... - Writing the number twice, first assuming it's greater than 10, and then correcting if it's smaller.
- Exit instruction is at an obscure address
11b, which contains the needed machine codeC3by luck.
C, 126 125 119 bytes
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]);}
Running:
$ gcc seq.c 2>& /dev/null
$ echo -n 'acbaabbbaaaaacc' | ./a.out
c=2
b=3
a=5
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])
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);}
}
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
CoffeeScript, 109 bytes
I like regex.
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'
Here is the compiled JavaScript you can try in your browser's console
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;
};
Then you can call
f("acbaabbbaaaaacc")
to get
c=2
a=5
b=3
Java Code: Out of interest I just found a solution will further enhance soon.
import java.util.HashMap;
import java.util.Map.Entry; import java.util.Scanner;
public class MaxSequenceLength { private HashMap characterCount = new HashMap<>();
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
new MaxSequenceLength().validateInput(inputScanner.nextLine());
inputScanner.close();
}
private void validateInput(String inputString) {
if (inputString.length() <= 1024) {
scanInput(inputString.toCharArray());
}
}
private void scanInput(char[] characterArrayInput) {
for (char tempCharacter : characterArrayInput) {
if ((int) tempCharacter < 65
|| ((int) tempCharacter > 90 && (int) tempCharacter < 97)
|| (int) tempCharacter > 122) {
continue;
} else if (characterCount.containsKey(tempCharacter)) {
characterCount.put(tempCharacter,
characterCount.get(tempCharacter) + 1);
} else {
characterCount.put(tempCharacter, 1);
}
}
for (Entry<Character, Integer> tempEntry : characterCount.entrySet()) {
System.out.println(tempEntry.getKey() + " = "
+ tempEntry.getValue());
}
}
}
The code would ignore all the other symbols and give only case sensitive character output.
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));}}
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!
CJam, 27 26 25 bytes
l:S_&{'=L{2$+_S\#)}g,(N}/
Example
$ cjam maxseq.cjam <<< "acbaabbbaaaaacc"
a=5
c=2
b=3
How it works
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. ";
}/ " ";
GolfScript, 26 bytes
:s.&{61{2$=}s%1,/$-1=,n+}%
Explanation:
:ssaves the input string in the variablesfor later use..&extracts the unique characters in the input, which the rest of the code in the{ }%loop then iterates over.61pushes the number 61 (ASCII code for an equals sign) on top of the current character on the stack, to act as an output delimiter.{2$=}s%takes the stringsand replaces its characters with a 1 if they equal the current character being iterated over, or 0 if they don't. (It also leaves the current character on the stack for output.)1,/takes this string of ones and zeros, and splits it at zeros.$sorts the resulting substrings,-1=extracts the last substring (which, since they all consist of repetitions of the same character, is the longest), and,returns the length of this substring.n+stringifies the length and appends a newline to it.
Ps. If the equals signs in the output are optional, the 61 can be omitted (and the 2$ replaced by 1$), for a total length of 24 bytes:
:s.&{{1$=}s%1,/$-1=,n+}%
Python (62 55)
n=raw_input()
print map(lambda x:[x,n.count(x)],set(n))
Old answer:
n=raw_input()
s=set(n)
print zip(s,map(lambda x:[x,n.count(x)],s))
Pyth, 24 25 26 (or 29)
=ZwFY{Z=bkW'bZ~bY)p(Yltb
Test can be done here: link
Outputs in the format:
('a', 5)
('c', 2)
('b', 3)
Explanation:
=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)
Python:
k=""
Z=copy(input())
for Y in set(Z):
b=copy(k)
while (b in Z):
b+=Y
print(_tuple(Y,len(tail(b))))
For proper (a=5) output, use:
=ZwFY{Z=bkW'bZ~bY)p++Y"="`ltb
29 characters
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 )
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
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 }
Mathematica, 74 72 69
Print[#[[1,1]],"=",Max[Tr/@(#^0)]]&/@Split@Characters@#~GatherBy~Max&
% @ "acbaabbbaaaaacc"
a=5 c=2 b=3
Not very good but strings are not Mathematica's best area. Getting better though. :-)
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 ]
J - 52 bytes
Well, a simple approach again.
f=:([,'=',m=:":@<:@#@[`(]m~[,{.@[)@.(+./@E.))"0 1~~.
Explanation:
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 + '='
Example:
f 'acbaabbbaaaaacc'
a=5
c=2
b=3
f 'aaaabaa'
a=4
b=1
If free-form output is allowed (as in many other answers), I have a 45 bytes version too. These boxes represent a list of boxes (yes, they're printed like that, although SE's line-height breaks them).
f=:([;m=:<:@#@[`(]m~[,{.@[)@.(+./@E.))"0 1~~.
f 'acbaabbbaaaaacc'
┌─┬─┐
│a│5│
├─┼─┤
│c│2│
├─┼─┤
│b│3│
└─┴─┘
f 'aaaabaabba'
┌─┬─┐
│a│4│
├─┼─┤
│b│2│
└─┴─┘
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
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}
Ruby, 72
(a=$*[0]).chars.uniq.map{|b|puts [b,a.scan(/#{b}+/).map(&:size).max]*?=}
This takes input from command line arguments and outputs to stdout.
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}
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)]