Letras do mesmo número


19

As letras das palavras querem justiça.

Eles decidiram aparecer o mesmo número de vezes em uma frase igualmente.

Exemplo:

Priorities

Se tornará:

Ppprrioooritttieeesss

Cada letra aparece 3 vezes, como a letra mais comum i, aparecendo 3 vezes.

Não importa onde você coloca as letras repetidas, desde que elas estejam próximas a uma letra semelhante.

Ou seja:

Pppriooorritttieeesss está OK (a letra 'r')

Ppprioororitttieeesss não está bom (a letra 'r')

Outro exemplo:

invoice

Se tornará:

innvvooiccee

Outro exemplo:

Remittance Advice

Se tornará:

Rrremmmiitttaannncce Adddvvvice

Espaço, vírgula, ponto de interrogação, cotação etc. não são considerados letras para esse desafio. Só precisa considerar [a-zA-Z]. Apenas uma vez o espaço é suficiente, e a ordem das letras deve permanecer a mesma.

A maiúscula não importa, maiúsculas e minúsculas são contadas como a mesma letra. Ou seja: Piptem 2 'P's e 1' I ', então ele se tornará Piip.

É maiúsculas e minúsculas que as letras podem estar em qualquer forma, Piip=piip=piiP=PiiP

Isso é


2
Posso sugerir o uso do Sandbox para desafios futuros, para ajudar a resolver todos os detalhes antes de postar a pergunta
Jo King

"Rrreeemmmiiitttaaannncccdddvvv" é uma saída aceitável no exemplo dado (uma vez que a ordem das letras distintas (definidas como az) ainda é mantida)? (My Jelly resposta atualmente conta com esta interpretação ser OK.)
Jonathan Allan

1
@ JonathanAllan Hmm, embora eu deixe a opção para OP, eu duvido muito. Não são apenas os caracteres que não são da letra (o espaço), mas você também coloca todos os caracteres um ao lado do outro em vez de mantê-lo no mesmo local. Sua saída torna o desafio diferente e mais fácil (imho).
Kevin Cruijssen

1
@KevinCruijssen o espaço está à esquerda - não é uma carta que, portanto, não precisa aderir a "e a ordem das letras deve permanecer o mesmo"
Jonathan Allan

1
@ JonathanAllan Ah, não percebi o espaço, meu mal. Entendo completamente o raciocínio que você forneceu na sua resposta do Jelly e com base no fato de que é realmente uma saída válida, mas eu prefiro ver o fraseado alterado, em vez de permitir o seu resultado, pois isso mudaria completamente o próprio desafio.
Kevin Cruijssen

Respostas:


5

05AB1E , 16 bytes

lDáÙSйls¢Zα>×.;

Experimente online!

Explicação

l                  # convert input to lowercase
 D                 # duplicate
  á                # keep only letters
   Ù               # remove duplicates
    S              # split to list of chars
     Ð             # triplicate
      ¹ls¢         # count the occurrences of each letter in lowercase input
          Zα       # absolute valuue with max occurrence
            >      # increment
             ×     # repeat each unique char that many times
              .;   # replace the first occurrence of the char in lowercase input with this

7

R , 106 bytes

function(s){for(A in L<-LETTERS)s=sub(A,strrep(A,max(x<-+s-+Map(gsub,L,'',s,T))-x[A]--1),s,T);s}
"+"=nchar

Experimente online!

Abordagem Base R:

  • roubando algumas idéias da abordagem @ J.Doe R + stringr , salvei 26 bytes!
  • outros 5 bytes salvos usando a sugestão @ J.Doe para abusar do +operador R

Estou impressionado que você tenha 111 com base-R!
J.Doe

@ J.Doe: Depois de publicar o meu original 137 bytes solução, eu um pouco mudou minha abordagem inspirado por seu, e eu basicamente convergiram para a sua solução, apenas com stringr removidos: D
digEmAll

1
106 bytes com abuso do operador. Base-R vence!
J.Doe

@ J.Doe: incrível!
precisa saber é o seguinte

5

Perl 6 , 82 bytes

-3 bytes graças a nwellnhof

->\a{a.=lc.=subst($_,$_ x a.comb(/<:L>/).Bag.values.max+1-a.comb($_))for 'a'..'z'}

Experimente online!

Pega uma sequência mutável e modifica-a no lugar.

Explicação:

->\a{        # Anonymous code block that takes a mutable string            }
 a.=lc;  # Lowercase
                                                               for 'a'..'z'  # For each letter
 .=subst(                                                    )  # Substitute
          $_,   #The first occurrence of the letter with
             $_ x  #The letter repeated
                  a.comb(/<:L>/).Bag.values.max    # The count of the most common letter
                                                 +1  # Plus 1
                                                   -a.comb($_)  # Minus the count of that letter already in the string

Você pode encadear o .=operador como a.=lc.=subst(...). Não tenho certeza se é permitido alterar o caso de uma letra existente. Também em <:L>vez de <:Ll>.
Nwellnhof 4/10

@nwellnhof Sim, o consulente diz que a saída é insensível caso
Jo rei

5

JavaScript (ES6), 112 bytes

s=>(m=g=F=>s.replace(/[a-z]/gi,c=>F(c.toLowerCase())))(c=>g[c]=c+c.repeat(m-g[c]),g(c=>m=(n=g[c]=-~g[c])<m?m:n))

Experimente online!

Comentado

s => (                       // s = input string
  m =                        // m = max. number of occurrences of the same letter
  g = F =>                   // g = helper function taking a callback function F
    s.replace(               //     (also used to store the # of occurrences of each letter)
      /[a-z]/gi,             //   for each letter c in s:
      c => F(                //     invoke F():
        c.toLowerCase()      //       with c.toLowerCase()
      )                      //     end of call to F()
    )                        //   end of replace()
)(c =>                       // invoke g() (second pass):
  g[c] =                     //   update g[c] to a non-numeric value
    c +                      //   append c once, unconditionally
    c.repeat(m - g[c]),      //   and append c as many times as required to reach m
                             //   (any subsequent iteration with the same letter will
                             //   lead to c.repeat(m - g[c]) --> c.repeat(NaN) --> '')
  g(c =>                     //   invoke g() (first pass):
    m = (n = g[c] = -~g[c])  //     increment g[c], save the result in n
      < m ? m : n            //     and update m to max(m, n)
  )                          //   end of first pass
)                            // end of second pass

Habilidades meu JS chupar, por isso estou um pouco confuso sobre esta parte: o[l] = // updates o[l] to a non-numeric value. Se bem entendi, oexiste uma matriz inteira nas funções Fe g, mas muda para uma matriz de cadeias contendo uma ou mais vezes o caractere cna parte que mencionei anteriormente? Além disso, acho que os valores de osão undefinedpor padrão, já que você está usando em o[l]=-~o[l]vez de ++o[l]?
Kevin Cruijssen

1
@KevinCruijssen Queremos que cada letra seja preenchida com o número máximo de ocorrências apenas uma vez. Ao atualizar o[l]para uma letra, qualquer iteração subsequente com a mesma letra levará a m - o[l] --> NaN(número inteiro menos letra) e l.repeat(NaN) == ''. (Sobre o último ponto: sim, isso é correto.)
Arnauld

Ah ok, obrigado pela explicação! :)
Kevin Cruijssen

(e eu deveria ter dito corda ao invés de letra )
Arnauld

5

J , 33 56 46 bytes

t=:~:tolower
(#~1+t*~:(*>./-])t*1#.e.)@toupper

Experimente online!

Não foi possível encontrar uma maneira de evitar o uso ~:tolowerduas vezes.

Como funciona

t=:~:tolower    Auxiliary function: isupper
     tolower    Is lowercase version of itself...
   ~:           different from itself?

(#~1+t*~:(*>./-])t*1#.e.)@toupper    Main function
                          toupper    Convert to uppercase
                      e.     Build 2D array by comparing to itself
                   1#.       Row-wise sum; Count occurrences
                 t*     A) Filter by isupper (needed for finding max count)
           >./-]        Compute max of A) minus each element of A)
       ~:          Nub sieve; 1 if first occurrence, 0 otherwise
          *        Filter first occurrences only
     t*       Filter by isupper again, to ban non-alphabets from duplicating
   1+         Add one to preserve given chars
 #~           Duplicate

5

R + stringr, 108 bytes

Eu não sou muito bom nisso stringr. Retorna uma mistura de letras minúsculas e maiúsculas, pois a pergunta diz que não importa.

function(x){for(l in L<-letters)x=sub(l,strrep(l,max(s<-stringr::str_count(tolower(x),L))-s[L==l]+1),x,T);x}

Experimente online!

Explicação

function(x){
for(l in letters){ # Iterate through builtin vector "a", "b", "c"...
   # Generate a 26-long integer vector for how many a's, b's, c's in lower case string
  s = stringr::str_count(tolower(x),letters)
    # Take the max of this
  m = max(s)
    # Repeat the letter in the iteration enough times to make the word 'fair'
  new.l = strrep(l,m-s[letters==l]+1)
    # Substitute the first instance only of the letter in the string for the repeated letter
    # This is case insensitive (the T at the end)
    # Notice we calculate the max letter frequency each loop
    # This is inefficient but doesn't change the answer and avoids bytes
  x=sub(l,new.l,x,T);
  }
x # Return the substituted string
}

3

K4 , 35 bytes

Solução:

{x@o@<o:(&^x),/(|/#:'g)#'g:" "_=_x}

Exemplos:

q)k){x@o@<o:(&^x),/(|/#:'g)#'g:" "_=_x}"Priorities"
"PPPrrioooritttieeesss"
q)k){x@o@<o:(&^x),/(|/#:'g)#'g:" "_=_x}"invoice"
"innvvooiccee"
q)k){x@o@<o:(&^x),/(|/#:'g)#'g:" "_=_x}"Remittance Notice"
"RRRemmmiittaaanncce Noootice"

Explicação:

Pode ser jogável com uma abordagem diferente, continuará pensando

{x@o@<o:(&^x),/(|/#:'g)#'g:" "_=_x} / the solution
{                                 } / lambda taking implicit argument x
                                _x  / lowercase input
                               =    / group
                           " "_     / drop space from keys
                         g:         / save as g
                       #'           / take each
               (      )             / do this together
                  #:'g              / count occurances in each group
                |/                  / take the maximum
             ,/                     / flatten with
        (&^x)                       / indices where input is null (ie " ")
      o:                            / save as o
     <                              / indices to sort o ascending
   o@                               / apply these to o
 x@                                 / apply these indices to original input

3

Carvão , 33 32 bytes

⭆↧θ⁺§θκ×ι∧№βι∧⁼κ⌕↧θι⁻⌈Eβ№↧θλ№↧θι

Experimente online! Link é a versão detalhada do código. Explicação:

  θ                                 Input string
 ↧                                  Lower case
⭆                                   Map over characters and join
      κ                             Current index
     θ                              Input string
    §                               Original character
   ⁺                                Concatenate with
        ι                           Lowercased character
       ×                            Repeated
            ι                       Lowercased character
           β                        Lowercase alphabet
          №                         Count
         ∧                          Logical And
                   ι                Lowercased character
                  θ                 Input string
                 ↧                  Lower case
                ⌕                   Find
               κ                    Current index
              ⁼                     Equals
             ∧                      Logical And
                       β            Lowercase alphabet
                      E             Map over characters
                           λ        Current character
                          θ         Input string
                         ↧          Lower case
                        №           Count
                     ⌈              Maximum
                    ⁻               Minus
                               ι    Lowercased character
                              θ     Input string
                             ↧      Lower case
                            №       Count
                                    Implicitly print

3

Java 11, 190 176 162 bytes

s->{s=s.toUpperCase();char m=2,i=64,a[]=new char[127];for(int c:s.getBytes())m-=m+~++a[c]>>-1;for(;++i<91;)s=s.replaceFirst(i+"",repeat((i+""),m-a[i]));return s;}

-14 bytes graças a @Nevay .

A saída está em maiúsculas completa.

Experimente online. (NOTA: String.repeat(int)é emulado como repeat(String,int)para a mesma contagem de bytes, porque o Java 11 ainda não está no TIO.)

Explicação:

s->{                      // Method with String as both parameter and return-type
  s=s.toUpperCase();      //  Convert the input-String to full uppercase
  char m=2,               //  Max occurrence (+1), starting at 2
       i=64,              //  Index integer, starting at 64 ('A'-1)
       a[]=new char[127]; //  Create a count-array of size 127 (printable ASCII chars)
  for(int c:s.getBytes()) //  Loop over the characters of the String as integers
    m-=m+~++a[c]>>-1;     //   Increase the occurrence-counter of the char by 1 first
                          //   And if it's larger than the max-2, increase the max by 1
  for(;++i<91;)           //  Loop `i` in the range ['A', 'Z']
    s=s.replaceFirst(i+"",//   Replace the first char `i` in the string with:
       (i+"").repeat(     //   That same character repeated
        m-a[i]));         //   The max(+1) minus its array-occurrence amount of times
  return s;}              //  Then return the now modified String as result

Você pode usar var para um byte?
Quintec

@ Quintec Em vez do que charvocê quer dizer? Infelizmente não. varsó pode ser usado para campos únicos. Então, em vez char m=1,i=127,a[]=new char[i];disso seria var m=1;var i=127;var a=new char[i];. Aqui está uma dica útil do que você pode ou não fazer com o Java 10 var. (Eu poderia substituir o intno circuito com var, mas o byte-count permaneceria a mesma.)
Kevin Cruijssen

Entendi, obrigado. Ainda não tenho idéia de como o Java 9/10/11 funciona, haha, continuarei com 8; p
Quintec 4/18/18

@ Quintec Java 9 Eu também realmente não entendo, uma vez que é principalmente focado nesse REPL. O Java 10 é basicamente o mesmo que o Java 8, exceto o var. E o Java 11 quase não tem alterações relacionadas ao codegolf, exceto pelo String.repeatmétodo que eu já usei várias vezes. Ele também possui o novo String.stripLeadingor String.stripTrailing, que age como trimapenas os espaços em branco à esquerda / à direita e String.isBlank()é o mesmo que String.trim().isEmpty()(somente espaço em branco ou espaço em branco).
Kevin Cruijssen

1
-14 bytes:s->{s=s.toUpperCase();char m=2,i=91,a[]=new char[127];for(int c:s.getBytes())m-=m+~++a[c]>>-1;for(;i-->65;)s=s.replaceFirst(i+"",repeat((i+""),m-a[i]));return s;}
Nevay

3

Japonês -h , 27 bytes

-3 bytes de @ETHproductions

;v
ñ oC ó¥ ú £=iXÎpXèS)UbXg

Tentando explicar

;v                          Convert implicit input to lowercase
ñ oC ó¥ ú £=iXÎpXèS)UbXg      Main function. Implicit lowercase input => "priorities"
ñ                           Sort => "eiiioprrst"
 oC                         Remove non alphabetical chars
   ó¥                       Split on different letters => ["e","iii","o","p","rr","s","t"]
     ú                      Right-pad each to the length of the longest with space => ["e  ","iii","o  ","p  ","rr ","s  ","t  "]
       £                    For each X in this array:
             XèS              Count the number of spaces in X
          XÎ                  Get the first character in X
            p   )             Repeat it (number of spaces) times
                              example the mapped value "e  " will become "ee"
         i                    Insert this into U at
                 UbXg           the first index of (first character in X) in U
        =                     Set U to the result

Experimente online!


1
Espero que você não se importe, eu ampliei parte da explicação (aquela linha que explicava o que cerca de 10 caracteres fazia de uma só vez: P) O útruque é genial, btw :-)
ETHproductions

@ETHproductions Eu aprecio isso. Eu não sou muito bom em inglês, por isso obrigado
Luis felipe De jesus Munoz

1
Infelizmente, parece falhar quando não há letras envolvidas (elas não devem ser alteradas). Uma correção simples seria inserir um ñ oC ó¥, embora exija a adição de ;...
ETHproductions

Espere ... desde quando ñfuncionou nas cordas ?! @ETHproductions, por favor, diga-me que é uma adição recente e eu não a ignorei esse tempo todo!
Shaggy

@Shaggy Aparentemente era 2,5 meses atrás --mas não se preocupe, eu mesmo tinha esquecido que existia até esta resposta ;-)
ETHproductions

2

Ruby , 89 bytes

->s{1while(a=s.scan /\w/).map(&g=->x{s.scan(/#{x}/i).size}).uniq[1]&&s[a.min_by &g]*=2;s}

Experimente online!

Tentei abordagens diferentes, mas o que realmente economiza muitos bytes é adicionar um caractere de cada vez.

Quão:

->s{
    1while                             # 1 is a nop to the while
    (a=s.scan /\w/)                    # For all the letters in the string
    .map(&g=->x{s.scan(/#{x}/i).size}) # Count occurrences ignoring case.
    .uniq[1]                           # Break out of loop if all equals
    &&s[a.min_by &g]*=2                # Otherwise duplicate the letter
                                       #  with the lowest count
    ;s}                                # Return the string

2

PowerShell 6, 123 bytes

Ele usa um intervalo de caracteres 'a'..'z'. Veja o script do PowerShell anterior abaixo.

param($s)for(;'a'..'z'|%{
if($d=($s-replace"[^$_]").Length-$n){if($d-gt0){1}else{$s=$s-replace"^(.*$_)","`$1$_"}}}){$n++}$s

Script de teste explicado:

$f = {

param($s)                               # a parameter string
for(;                                   # loop while exists at least one letter...
'a'..'z'|%{                             # for each letter
    $d=($s-replace"[^$_]").Length-$n    # let $d is a difference between a number of current letter and current $n 
    if($d-gt0){                         # if the difference > 0
        1                               # then return a object to increase $n on next iteration
    }
    if($d-lt0){                         # if the differenct < 0
        $s=$s-replace"^(.*$_)","`$1$_"  # append the current letter after a last instance of the letter. Use "^(.*?$_)" regexp to append it after a first instance of the letter.
    }
}){
    $n++                                # increment $n if exists at least one letter number of witch greather then $n
}                                       # and make next iteration of the 'for'.

$s                                      # return modified string if all letters in the string occur the same number of times

}

@(
    ,('Priorities', 'Ppprrioooritttieeesss', 'PPPriooorritttieeesss')
    ,('invoice', 'innvvooiccee')
    ,('Remittance Advice', 'Rrremmmiitttaannncce Adddvvvice', 'RRRemmmitttannnce Aadddvvviicce')
) | % {
    $s,$e = $_
    $r = &$f $s
    "$($r-in$e): $r"
}

Resultado:

True: Pppriooorritttieeesss
True: innvvooiccee
True: Rrremmmitttannnce Aadddvvviicce

Powershell 5.1-, 133 bytes

param($s)for(;97..122|%{$_=[char]$_
if($d=($s-replace"[^$_]").Length-$n){if($d-gt0){1}else{$s=$s-replace"^(.*$_)","`$1$_"}}}){$n++}$s

2

Vermelho , 252 bytes

func[s][a: charset[#"a"-#"z"#"A"-#"Z"]t: parse s[collect[any[keep a | skip]]]m: copy
#()foreach c t[c: form c either n: m/:c[m/:c: n + 1][m/:c: 1]]d: last sort extract next
to-block m 2 foreach c s[prin c: form c if n: m/:c[loop d - n[prin c]m/:c: d]]]

Experimente online!

Solução ridiculamente longa ...

Explicação:

f: func [ s ] [
    a: charset [ #"a" - #"z" #"A" - #"Z" ]   ; letters
    t: parse s [                             ; parse the string 
        collect [ any [ keep a | skip ] ]    ; and keep only the letters
    ]
    m: copy #()                              ; initialize a map
    foreach c t [                            ; for each character in t
        c: form c                            ; the character as a string
        either n: select m c [ m/:c: n + 1 ] ; increase the count if already in map
                             [ m/:c: 1 ]     ; otherwise create a map entry with count 1 
    ]
    d: last sort extract next to-block m 2   ; convert the map to a block; extract only the 
                                             ; numbers and take the last of the sorted block
    foreach c s [                            ; for each character in the input
        c: form c                            ; the character as a string
        prin c                               ; print it (with no space nor newline)
        if n: select m c [                   ; if c is a key in the map
            loop d - n [ prin c ]            ; print the character again up to d times 
            m/:c: d                          ; set the count to max (flag it as used)
        ]
    ]
]

2

JavaScript (Node.js) , 140 137 bytes

x=>[...x=x.toLowerCase()].map(F=c=>(F[c]=-~F[c],F[c]>w?w=F[c]:w,c),w=0).map(c=>x=x.replace(c,c.repeat(c>'`'&c<'{'?w-F[c]+1:1),F[c]=w))&&x

Experimente online!

+33 bytes da minha primeira solução para essas restrições adicionais intermináveis. JS é péssimo com as manipulações de string que não diferenciam maiúsculas de minúsculas.

-3 bytes de volta Obrigado @Arnauld.

Explicação

x =>                                     // The function.
  [...x = x.toLowerCase()].map(f = c => (// - Iterate among each character...
                                         // - Additional constraint 2
    f[c] = -~f[c],                       //   - Add one to the character counter
    f[c] > w ? w = f[c] : w,             //   - Update the maximum count if necessary
    c                                    //   - Return back the character for the use in
                                         //     the next map function
  ), w = 0)                              // - The counters
  .map(c =>                              // - Iterate again...
    x = x.replace(                       //   - Repeat the first appearance of
      c,                                 //   - Each character
      c.repeat(                          //   - Needed number times
        c > '`' & c < '{'                //   - Additional constraint 1
        ? w - f[c] + 1                   //   - If this is letter, repeat
        : 1                              //   - If not, stay as is
      ),                                 //   - That should've been clearly stated
      f[c] = w                           //   - And set the counter so that no further 
                                         //     replacements are done on this character 
    )                                    //   - (w - f[c] + 1 = 1 in further iterations)
  ) && x                                 // - Return the result

As soluções precisam ser capazes de lidar com entradas de casos mistos.
Shaggy

@ Shagy Acho que o desafio foi editado após o seu comentário. Parece que o caso da saída não importa.
Arnauld

Por outro lado, as funções devem ser reutilizáveis , o que não é o caso aqui.
Arnauld

@Arnauld Oh eu às vezes vê-lo usando fs como armazenamento temporário, então eu pensei que está tudo bem
Shieru Asakoto

map()As funções de retorno de chamada são seguras para uso em armazenamento, porque são definidas em um escopo local. Usar a função principal - que é definida globalmente - é mais perigoso. Aqui, você pode usar o retorno de chamada do primeiro map(), que o leva de volta a 137 bytes .
Arnauld

2

Casca , 15 bytes

ḟ§Ë#f√MṘO´πL¹m_

Experimente online!

Força bruta, muito lenta.

Explicação

ḟ§Ë#f√MṘO´πL¹m_  Implicit input, say s = "To do"
             m_  Convert to lowercase: t = "to do"
           L¹    Length of s: 5
         ´π      All length-5 combinations of [1..5]:
                   [[1,1,1,1,1], [1,1,1,1,2], [2,1,1,1,1], ..., [5,5,5,5,5]]
        O        Sort them lexicographically:
                   [[1,1,1,1,1], [1,1,1,1,2], [1,1,1,1,3], ..., [5,5,5,5,5]]
      MṘ         For each, replicate letters of t that many times:
                   ["to do", "to doo", "to dooo", ..., "tttttooooo     dddddooooo"]
ḟ                Find the first string that satisfies this:
                   Example argument: x = "tto ddo"
    f√             Letters of x: "ttoddo"
  Ë                They have equal
 § #               number of occurrences in x: true (all have 2).

não foi possível obter resultados
asmgx 06/10

@asmgx O programa é realmente muito lento. Parece esgotar o tempo limite no TIO para entradas de comprimento 8 ou mais, porque interrompe o cálculo após 1 minuto. O intérprete offline deve fornecer um resultado se você esperar o suficiente (provavelmente várias horas para as entradas com comprimento de 10).
Zgarb 06/10/19

2

Perl 6 , 77 70 bytes

{s:i|$($!.min(*{*}).key)|$/$/|until [==] ($!=.lc.comb(/<:L>/).Bag){*}}

Experimente online!

Adotando a abordagem do GB de inserir um caractere até que todos os caracteres apareçam o mesmo número de vezes. Recebe uma sequência que é modificada no local.

Se os sublinhados puderem ser tratados como letras, a regex poderá se tornar /\w/, economizando dois bytes.

Explicação

{
                    .lc.comb(/<:L>/).Bag          # Create Bag of letter/count pairs
                ($!=                    )         # Store temporarily in $!
 ... until [==]                          .values  # Until all counts are equal
 s:i|                      |    |                 # Replace (ignoring case)
     $($!.min(*.value).key)                       # letter with minimum count
                            $/$/                  # with itself doubled
}

@JoKing Parece que sua melhoria se baseia na versão antiga antes de eu descobrir o {*}truque.
nwellnhof 20/01

Então, isso é como um atalho .value(s), certo? Talvez eu precise atualizar algumas das minhas soluções antigas
Jo King


1

C (clang) , 246 223 220 210 208 193 188 bytes

Sinalizador do compilador -DF=;for(i=0;b[i];i++ -DB=b[i](29 bytes)

Adicionado suporte a caso misto.

f(char*c){char m,i,s,*b,a[255]={0};s=asprintf(&b,c)F)B=tolower(B),a[B]++F,a[B]>a[m]?m=B:0)F)a[B]^a[m]?b=realloc(b,s+i),bcopy(&B,b+i+1,s),a[B]++:(m=B);puts(b);}

Experimente online!


1

Pitão, 31 30 bytes

JeSm/Qd=r0QVQ=tQ=+k*N-J/+kQN)k

Experimente aqui

Explicação

JeSm/Qd=r0QVQ=tQ=+k*N-J/+kQN)k
       =r0Q                        Convert input to lowercase.
JeSm/Qd                            Find the count of the most common character.
           VQ               )      For each character in the input...
             =tQ                   ... remove that character from the input...
                =+k*N-J/+kQN       ... append copies to k until we have enough.
                             k     Output.

1

C (GCC) - 175 bytes

f(char*s){int c[999]={0},i=0,m=0,k,L;while((L=s[i++])&&(k=++c[L<97?L+32:L]))m=k>m?k:m;i=0;while(L=s[i++])for(L=L<97&&L>64?L+32:L,putchar(L);isalpha(L)&&++c[L]<=m;)putchar(L);}

Ungolfed

f(char *s) {
  int c[999]={0},i=0,m=0,k,L;                      // Array used like a dictionary, temp vars
  while((L=s[i++])&&(k=++c[L<97?L+32:L]))          // store letter counts
    m=k>m?k:m;                                     // calculate max occurance
  i=0;                                             // reset string index
  while(L=s[i++])                                  // iterate string
    for(L=L<97&&L>64?L+32:L,putchar(L);isalpha(L)&&++c[L]<=m;) // set character L to lowercase if in alphabet, print always once, repeat if in alphabet
      putchar(L);                                  // print character
}

Experimente online!


0

Kotlin Android, 413 bytes

var l: List<Char> = w.toList().distinct();val h = HashMap<Char, Int>();var x='m';var n=0;for(z in l.indices){var c=0;for (i in 0.rangeTo(w.length-1)){if(l[z]==(w[i]))c++};h.put(l[z],c);if(n<c){n=c}};for(entry in h){h.replace(entry.key,n-entry.value)};var v=ArrayList<Char>();for(i  in 0.rangeTo(w.length-1)){if(h.containsKey(w[i])){for(p in 0.rangeTo(h.get(w[i])!!)){v.add(w[i])};h.remove(w[i])}else{v.add(w[i])}}

Experimente on-line

Explicação etapa 1 -> Selecione a lista de caracteres distintos. passo 2 -> obtenha a contagem de todos os caracteres da string e selecione a frequência máxima de caracteres. passo 3 -> obtenha diferença na frequência de caracteres em relação à frequência máxima de caracteres passo 4 -> coloque caracteres em relação às posições na string. Resolução feliz!



0

PHP ,185 173 170 bytes

function($s){$m=max($a=count_chars($s=strtolower($s),1));foreach(str_split($s)as$c)$o.=str_repeat($c,($b=$a[$d=ord($c)])!=($a[$d]=$m)&&$d>96&&$d<123?$m-$b+1:1);return$o;}

Experimente online!

Ungolfed (e não ternário e não otimizado).

function f($s) {
    $s = strtolower( $s );
    $a = count_chars( $s, 1 );
    $m = max( $a );
    foreach( str_split( $s ) as $c ) {
        if ( $c < 'a' or $c > 'z') {           // is non a-z
            $n = 1;
        } elseif ( $a[ord($c)] == $m ) {    // already has max number
            $n = 1;
        } else {
            $n = $m - $a[ord($c)] + 1;       // add this many chars
        }
        $o .= str_repeat( $c, $n );
        $a[ord($c)] = $m;                   // has reached the max
    }
    return $o; 
}
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.