Trova la lunghezza massima della sequenza


29

Supponiamo di avere una stringa e vogliamo trovare la sequenza massima ripetuta di ogni lettera.

Ad esempio, dato l'input di esempio:

"acbaabbbaaaaacc"

L'output per l'input di esempio può essere:

a=5
c=2
b=3

Regole:

  • Il tuo codice può essere una funzione o un programma, a tua scelta
  • L'input può essere tramite stdin, file o parametro di funzione
  • L'output deve contenere solo caratteri che compaiono nell'input
  • La lunghezza massima in ingresso è 1024
  • L'ordine di uscita non ha importanza, ma deve essere stampato nel formato [char] = [massima sequenza ripetuta] [delimitatore]
  • La stringa può contenere qualsiasi carattere

La competizione termina giovedì 3 alle 23:59 UTC.


Esiste un massimo per la lunghezza della stringa di input?
— sigma,

2
L'output deve essere esattamente come indicato? Possiamo dire 0 per lettere che non compaiono? Ogni lettera fino alla lettera più alta apparirà almeno una volta?
— xnor

1
Si prega di chiarire se l'output deve essere formattato esattamente come esemplificato nella domanda. Almeno 10 delle 16 risposte attuali utilizzano un formato diverso, altre tre presentano due versioni diverse.
— Dennis,

1
@Joey Probabilmente dovresti punire per il golf. Se lo perdoni, finirò per vedere l:S_&{'=L{2$+_S\#)}g,(N}/nei sistemi di produzione! E maledirò il tuo nome.
— Cruncher,

Risposte:


22

8086 codice macchina, 82 80

Contenuto del x.comfile:

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

Supporta solo ripetizioni fino a 99 caratteri.

Codice sorgente (servito come input per l' debug.comassemblatore), con commenti!

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

Ecco alcune tecniche di golf utilizzate qui che penso siano state divertenti:

  • l'indirizzo dell'array è 3d00, dove si 3dtrova il codice ASCII =. In questo modo, l'indirizzo per l'inserimento dell'array per il caratterex è 3d78. Se interpretato come una stringa di 2 caratteri, lo è x=.
  • Il buffer di output è all'indirizzo 104 ; sovrascrive il codice di inizializzazione che non è più necessario. La sequenza di fine riga 0D 0A 24viene eseguita come codice innocuo.
  • Il aam istruzioni qui non forniscono alcun golf, anche se potrebbe ...
  • Scrivendo il numero due volte, assumendo prima che sia maggiore di 10, quindi correggendo se è più piccolo.
  • Le istruzioni di uscita sono a un indirizzo oscuro 11b, che C3per fortuna contiene il codice macchina necessario .

Approccio interessante Tuttavia, con una limitazione di 99 ripetizioni, non gestirà i casi in cui viene fornito l'input di 1024 aaaa.
— Homer6,

14

CJam, 27 26 25 byte

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

Provalo online.

Esempio

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

Come funziona

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 byte

Bene, di nuovo un approccio semplice.

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

Spiegazione:

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 + '='

Esempio:

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

Se è consentito l'output in formato libero (come in molte altre risposte), ho anche una versione di 45 byte . Queste caselle rappresentano un elenco di caselle (sì, sono stampate in questo modo, anche se l'altezza della linea di SE le interrompe).

   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]*?=}

Questo porta l'input dagli argomenti della riga di comando e gli output su stdout.


charsè un po 'più corto di split("").
— Ventero,

@Ventero L'ho provato, ma charsfornisce un enumeratore anziché un array. Sono in 1.9.3, quindi è una cosa 2.0?
— afuoso

Sì, in 2.0 charsrestituisce un array.
— Ventero,

Potrebbe allungare un po 'le regole, ma forse usare al pposto di puts?
— Shelvacu,

1
Vedo. Anche se questo lo rende meno carino, non riesco a vedere che avrebbe infranto qualsiasi regola.
— daniero,

7

GolfScript, 26 byte

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

Provalo online.

Spiegazione:

  • :ssalva la stringa di input nella variabile sper un uso successivo.
  • .&estrae i caratteri univoci nell'input, su cui scorre il resto del codice nel { }%ciclo.
  • 61 spinge il numero 61 (codice ASCII per un segno di uguale) sopra il carattere corrente nello stack, per fungere da delimitatore di output.
  • {2$=}s%prende la stringa se sostituisce i suoi caratteri con 1 se uguagliano il carattere corrente su cui viene ripetuta, o 0 se non lo fanno. (Lascia anche il carattere corrente nello stack per l'output.)
  • 1,/ prende questa stringa di uno e zeri e la divide in zeri.
  • $ordina le sottostringhe risultanti, -1=estrae l'ultima sottostringa (che, poiché sono tutte costituite da ripetizioni dello stesso carattere, è la più lunga) e ,restituisce la lunghezza di questa sottostringa.
  • n+ specifica la lunghezza e vi aggiunge una nuova riga.

Ps. Se i segni di uguale nell'output sono opzionali, 61possono essere omessi (e 2$sostituiti da 1$), per una lunghezza totale di 24 byte :

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

1
È possibile salvare lo swap se si preme la 61prima: :s.&{61{2$=}s%1,/$-1=,n+}%.
— Howard,

@Howard: grazie!
— Ilmari Karonen,

6

CoffeeScript, 109 byte

Mi piace 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'

Ecco il JavaScript compilato che puoi provare nella console del tuo browser

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;
};

Quindi puoi chiamare

f("acbaabbbaaaaacc")

ottenere

c=2
a=5
b=3

Questo sembra generare risultati errati per input come aaaabaa.
— Ventero,

@Ventero hai ragione, ci sono due problemi. uno si risolve facilmente, ma devo pensare all'altro.
— Martin Ender,

@Ventero risolto.
— Martin Ender,

5

Pyth , 24 25 26 (o 29)

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

Il test può essere fatto qui: link

Output nel formato:

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

Spiegazione:

=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)

Pitone:

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

Per un'uscita corretta (a = 5), utilizzare:

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

29 caratteri


Sembra che tu abbia avuto la stessa identica idea. Avere un +1 per quello.
— Seequ,

@ TheRare sì, sembra un ottimo modo per farlo.
— isaacg,

Non proprio correlato al tuo algoritmo, ma l'output di Python è confuso, perché k=''è definito altrove.
— gggg

Sì, scusa per quello. Lavorerò per migliorarlo. Lo modificherò anche io.
— isaacg,

5

C, 126 125 119 byte

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]);}

In esecuzione:

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

Potresti sostituirlo getchar()>0con ~getchar()like in questa risposta
— anatolyg

@anatolyg EOF è garantito per essere esattamente -1? Ho pensato che fosse specificamente definito come <0.
— soffice

Penso che -1 sia abbastanza comune (cioè Windows e Linux), quindi puoi assumerlo per Code Golf. Per il codice di produzione, less than zeroè perfettamente OK, ma == EOFè più chiaro.
— Anatolyg,

@anatolyg Certo, e in realtà suppongo che secondo le specifiche EOF non sia nemmeno garantito essere <0 - potrebbe anche essere, ad esempio, 256. Quindi salverò solo il singolo byte. :)
— soffice

2
EOFè garantito per essere negativo e -1 viene utilizzato anche se charè firmato; vedi qui
— anatolyg

4

Mathematica , 74 72 69

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

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

Non molto buono, ma le stringhe non sono la migliore area di Mathematica . Stare meglio però. :-)


Questo golf è piuttosto impressionante (dicendo questo dopo averlo provato io stesso ...)
— Szabolcs,

v10, non una soluzione completa: First@*MaximalBy[Length] /@ GroupBy[First]@Split@Characters[#] & almeno è abbastanza semplice e leggibile.
— Szabolcs,

@Szabolcs Grazie! Qual è la differenza tra GroupBye GatherBy?
— Mr.Wizard,

La differenza principale è che GroupByrestituisce un Association. Non ho ancora studiato le altre differenze nei dettagli. reference.wolfram.com/language/ref/GroupBy.html Puoi provarlo nel cloud con un account gratuito (è così che sto giocando con questi).
— Szabolcs,

3

C # (LinQPad)

146

Questa è la risposta di Tsavino ma più breve. Qui, ho usato Distinct()invece di GroupBy(c=>c). Anche le parentesi graffe dal foreach-loopvengono lasciate fuori:

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

Ho provato a utilizzare una lambda expressionsintassi della query invece della normale ma poiché avevo bisogno di una Cast<Match>prima, il codice è diventato più lungo di 1 carattere ... Comunque, poiché può essere eseguito in LinQPad, puoi usare Dump()invece di 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();}

Un ulteriore studio del codice mi ha fatto pensare al Max(). Questa funzione accetta anche a Func. In questo modo potrei saltare la Selectparte usando l'epxression lambda:

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

Pertanto, il risultato finale:

128

Aggiornare:

Grazie al suggerimento di Dan Puzey, sono stato in grado di salvare altri 6 personaggi:

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

Lunghezza:

122


Grazie per i tuoi miglioramenti, non sapevo del trucco con .Dump () in LinqPad. Ad essere sincero, ho sviluppato il codice in Visual Studio e l'ho copiato in LinqPad per salvare alcuni caratteri perché LinqPad non ha bisogno di un metodo principale.
— Tsavinho,

Grazie! Ho anche avuto modo di conoscere ilDump() metodo di recente, risparmiando 10+ caratteri ogni volta :) Le parentesi graffe sono state facili e il resto è stato un po 'intrigante: D
— Abbas,

1
Se sei felice di usare lo IEnumerablestile di visualizzazione di LinqPad puoi salvare altri 8 caratteri, con questo come il tuo corpo: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)

Anche il golf Python può essere molto leggibile. Penso che questo codice sia completamente idiomatico ad eccezione delle variabili a lettera singola e di una riga mentre il ciclo.

Esempi di esecuzione:

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

Questa è una soluzione interessante
— Cruncher,

1
se cambi set (s) in solo s penso che soddisfi ancora i requisiti. Da nessuna parte si dice che ogni carattere deve essere stampato una sola volta.
— Cruncher,

@Cruncher Sono d'accordo che l'OP non specifichi ogni lettera una volta, ma le altre risposte di Python sembrano assumerlo, quindi mi atterrò per essere comparabile. Sebbene i formati di output siano ancora incoerenti. Vorrei che il PO avesse risposto alle richieste di chiarimento.
— xnor

2

Ruby, 58 anni

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

Riceve input da STDIN, lo invia a STDOUT nel modulo {"a"=>5, "c"=>2, "b"=>3}


2

C # in LINQPad - 159 byte

Beh, almeno ho battuto T-SQL; P Non batterò nessun altro, ma ho pensato di condividerlo comunque.

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());}}

Uso:

v("acbaabbbaaaaacc");

I suggerimenti sono sempre ben accetti!


Bella risposta! Ho alcuni suggerimenti, ma era troppo lungo per un commento, quindi fai clic qui per la mia risposta. :)
— Abbas,

2

Powershell 80 77 72

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

Devi eseguirlo su console ...


1
$xè superfluo. Sei più corto di tre byte non utilizzandolo. È anche sort -usufficiente. Raramente è necessario precisare i nomi dei parametri completi. Questo, tuttavia, fallirà per alcuni personaggi a causa dell'uso senza escape nella regex. A seconda di come deve essere compreso »La stringa può contenere qualsiasi carattere«, questo potrebbe essere un problema.
— Joey,

@Joey grazie per il suggerimento su sort -u, tuttavia per quanto riguarda $ x non sono riuscito a farlo funzionare [char[]]"$args"|sort -u|%{"$_="+($args-split"[^$_]"|sort)[-1].length}, sembra che il secondo $ args si svuoti ... - darkajax 17 minuti fa
— DarkAjax

Sì, sì. Scusate. Questo perché si trova in un blocco di script, che ha i suoi argomenti (il $argsnon è più quello dello script).
— Joey,

2

Perl - 65 71 76 caratteri

Il mio primo codice golf!

Per ogni risposta, copia su golf.pl ed esegui come:

echo acbaabbbaaaaacc | perl golf.pl

La mia soluzione più breve stampa ogni personaggio quante volte sembra, dal momento che non è proibito dalle regole.

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

La mia soluzione più corta successiva (85 90 caratteri) stampa ogni personaggio una sola volta:

<>=~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, chiamando

f "acbaabbbaaaaacc"

dà

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); ...];}

Tuttavia, per stamparlo senza ulteriori informazioni, chiamalo così:

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

che dà

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

1

Javascript, 116 byte

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

Uscita campione:

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

Modifica: rimosso ORDER BYperché le regole consentono qualsiasi ordine di output.

Prende input da una variabile CHAR @ae utilizza un CTE ricorsivo per creare una riga per ogni carattere nella stringa e calcola occorrenze sequenziali.

Dopodiché, è un semplice SELECTe in GROUP BYconsiderazione per l'ordine dell'output.

Provalo su 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

Assegnare la variabile:

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

Uscita campione:

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
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.