Stesso numero di lettere


19

Le lettere delle parole vogliono equità.

Hanno deciso di apparire allo stesso numero di volte in una frase allo stesso modo.

Esempio:

Priorities

Diventerà:

Ppprrioooritttieeesss

Ogni lettera appare 3 volte, come era la lettera più comune i, appare 3 volte.

Non importa dove metti le lettere ripetute, purché siano accanto a una lettera simile.

Vale a dire:

Pppriooorritttieeesss è OK (la lettera 'r')

Ppprioororitttieeesss non va bene (la lettera 'r')

Un altro esempio:

invoice

Diventerà:

innvvooiccee

Un altro esempio:

Remittance Advice

Diventerà:

Rrremmmiitttaannncce Adddvvvice

Spazio, virgola, punto interrogativo, citazione, ecc. Non sono considerati lettere per questa sfida. Devo solo considerare [a-zA-Z]. Solo una volta lo spazio è sufficiente e l'ordine delle lettere dovrebbe rimanere lo stesso.

La maiuscola delle lettere non ha importanza, le lettere maiuscole e minuscole sono conteggiate come la stessa lettera. Cioè: Pipha 2 'P e 1' I ', quindi diventerà Piip.

È possibile che le lettere senza distinzione tra maiuscole e minuscole possano essere in qualsiasi forma, Piip=piip=piiP=PiiP

Questo è


2
Potrei suggerire di usare il Sandbox per le sfide future per aiutare a chiarire tutti i dettagli prima di pubblicare la domanda sul principale
— Jo King

"Rrreeemmmiiitttaaannncccdddvvv" è un risultato accettabile nell'esempio dato (poiché l'ordine delle lettere distinte (definito come az) è ancora mantenuto)? (La mia risposta di Jelly attualmente si basa sul fatto che questa interpretazione sia OK.)
— Jonathan Allan,

1
@JonathanAllan Hmm, anche se lascio la scelta a OP, ne dubito fortemente. Non solo i caratteri non lettera (lo spazio) sono spariti, ma hai anche messo tutti i personaggi uno accanto all'altro invece di tenerlo nello stesso posto. Il tuo output rende la sfida diversa e più semplice (imho).
— Kevin Cruijssen,

1
@KevinCruijssen lo spazio è a sinistra - non è una lettera quindi non è necessario aderire a "e l'ordine delle lettere dovrebbe rimanere lo stesso"
— Jonathan Allan

1
@JonathanAllan Ah, non ho notato lo spazio, mio ​​male. Comprendo completamente il ragionamento che hai fornito nella tua risposta Jelly e basato sul fatto che è effettivamente un risultato valido, ma preferirei vedere il fraseggio cambiato, quindi consentire il tuo risultato, poiché cambierebbe completamente la sfida stessa.
— Kevin Cruijssen,

Risposte:


5

05AB1E , 16 byte

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

Provalo online!

Spiegazione

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 byte

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

Provalo online!

Approccio di base R:

  • rubando alcune idee dall'approccio @ J.Doe R + stringr , ho salvato 26 byte!
  • altri 5 byte salvati usando il suggerimento di @ J.Doe per abusare +dell'operatore R.

Sono impressionato che tu abbia 111 con base-R!
— J.Doe,

@ J.Doe: dopo aver pubblicato la mia soluzione originale di 137 byte, ho leggermente modificato il mio approccio ispirato al tuo, e fondamentalmente mi sono convertito alla tua soluzione, solo con stringr rimosso: D
— digEmAll

1
106 byte con abuso da parte dell'operatore. Base-R vince!
— J.Doe,

@J.Doe: fantastico!
— digEmAll

5

Perl 6 , 82 byte

-3 byte grazie a nwellnhof

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

Provalo online!

Prende una stringa mutabile e la modifica in posizione.

Spiegazione:

->\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

Puoi incatenare l' .=operatore come a.=lc.=subst(...). Non sono sicuro se sia consentito cambiare il caso di una lettera esistente. Anche <:L>invece di <:Ll>.
— nwellnhof,

@nwellnhof Sì, il richiedente chiede che l'output non fa distinzione tra maiuscole e minuscole
— Jo King,

5

JavaScript (ES6), 112 byte

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

Provalo online!

Commentate

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

Abilità Il mio JS schifo, quindi sono un po 'confuso su questa parte: o[l] = // updates o[l] to a non-numeric value. Se ho capito bene, oc'è un array intero nelle funzioni Fe g, ma cambia in un array di stringhe che contiene una o più volte il carattere cnella parte che ho menzionato prima? Inoltre, suppongo che i valori di osiano undefinedpredefiniti, poiché stai usando o[l]=-~o[l]invece di ++o[l]?
— Kevin Cruijssen,

1
@KevinCruijssen Vogliamo che ogni lettera sia riempita al massimo numero di occorrenze una sola volta. Aggiornando o[l]una lettera, ogni successiva iterazione con la stessa lettera porterà a m - o[l] --> NaN(intero meno lettera) e l.repeat(NaN) == ''. (Circa l'ultimo punto: sì, è corretto.)
— Arnauld

Ah ok, grazie per la spiegazione! :)
— Kevin Cruijssen,

(e avrei dovuto dire stringa piuttosto che lettera )
— Arnauld

5

J , 33 56 46 byte

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

Provalo online!

Impossibile trovare un modo per evitare di usarlo ~:tolowerdue volte.

Come funziona

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 byte

Non sono molto bravo a stringr. Restituisce una combinazione di lettere minuscole e maiuscole poiché la domanda dice che non 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}

Provalo online!

Spiegazione

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 byte

Soluzione:

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

Esempi:

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"

Spiegazione:

Potrebbe essere giocabile a golf con un approccio diverso, continuerà a pensare

{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

Carbone , 33 32 byte

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

Provalo online! Il collegamento è alla versione dettagliata del codice. Spiegazione:

  θ                                 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 byte

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 byte grazie a @Nevay .

L'output è in maiuscolo.

Provalo online. (NOTA: String.repeat(int)viene emulato come repeat(String,int)per lo stesso conteggio byte, poiché Java 11 non è ancora su TIO.)

Spiegazione:

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

Puoi usare var per un byte?
— Quintec,

@Quintec Invece di charintendi? Sfortunatamente no. varpuò essere utilizzato solo per singoli campi. Quindi invece char m=1,i=127,a[]=new char[i];sarebbe var m=1;var i=127;var a=new char[i];. Ecco un suggerimento utile su cosa puoi e cosa non puoi fare con Java 10 var. (Potrei sostituire il intnel ciclo con var, ma il conteggio dei byte rimarrebbe lo stesso.)
— Kevin Cruijssen,

Grazie, grazie. Non ho ancora idea di come funzioni Java 9/10/11, ahah, mi
— atterrò

@Quintec Java 9 Anche io non capisco, dato che si concentra principalmente su quel REPL. Java 10 è principalmente uguale a Java 8, ad eccezione di var. E Java 11 ha a malapena qualche modifica relativa a codegolf, fatta eccezione per il String.repeatmetodo che ho già usato un sacco di volte. Ha anche il nuovo String.stripLeadingo String.stripTrailing, che si comporta come trimma solo gli spazi bianchi iniziali / finali e String.isBlank()che è uguale a String.trim().isEmpty()(solo spazi vuoti o bianchi).
— Kevin Cruijssen,

1
-14 byte: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

Japt -h , 27 byte

-3 byte da @ETHproductions

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

Sto cercando di spiegare

;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

Provalo online!


1
Spero non ti dispiaccia, ho ampliato parte della spiegazione (quella riga che spiegava cosa facevano contemporaneamente circa 10 caratteri: P) Il útrucco è geniale, a proposito :-)
— ETHproductions

@ETHproductions Lo apprezzo. Non sono troppo bravo in inglese, quindi grazie
— Luis felipe De jesus Munoz,

1
Sfortunatamente, sembra fallire quando sono coinvolte non lettere (non dovrebbero essere cambiate). Una semplice soluzione sarebbe quella di inserire un ñ oC ó¥, anche se richiede l'aggiunta di nuovo nel ;...
— ETHproductions

Aspetta ... da quando ha ñfunzionato sulle stringhe ?! @ETHproductions, per favore dimmi che è un'aggiunta recente e non l'ho trascurato per tutto questo tempo!
— Shaggy,

@Shaggy Apparentemente era 2,5 mesi fa - ma non preoccuparti, anche se avevo dimenticato che esisteva fino a questa risposta ;-)
— ETHproductions

2

Rubino , 89 byte

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

Provalo online!

Ho provato approcci diversi, ma ciò che risparmia davvero molti byte è l'aggiunta di un carattere alla volta.

Come:

->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 byte

Utilizza una gamma di caratteri 'a'..'z'. Vedi lo script per Powershell precedente di seguito.

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

Script di prova spiegato:

$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"
}

Produzione:

True: Pppriooorritttieeesss
True: innvvooiccee
True: Rrremmmitttannnce Aadddvvviicce

Powershell 5.1-, 133 byte

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

2

Rosso , 252 byte

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]]]

Provalo online!

Soluzione ridicolmente lunga ...

Spiegazione:

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 byte

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

Provalo online!

+33 byte dalla mia prima soluzione per quei vincoli aggiuntivi infiniti. JS fa schifo a manipolazioni di stringhe insensibili al maiuscolo che conosci.

-3 byte indietro Grazie @Arnauld.

Spiegazione

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

Le soluzioni devono essere in grado di gestire input di casi misti.
— Shaggy,

@Shaggy Penso che la sfida sia stata modificata dopo il tuo commento. Sembra che il caso dell'output non abbia importanza.
— Arnauld,

D'altra parte, le funzioni devono essere riutilizzabili , il che non è il caso qui.
— Arnauld,

@Arnauld Oh, a volte ti vedo usare fs come memoria temporanea, quindi ho pensato che
— andasse

map()le funzioni di callback sono sicure da usare per l'archiviazione, poiché sono definite in un ambito locale. L'uso della funzione principale, definita a livello globale, è più pericoloso. Qui, è possibile utilizzare il callback del primo map(), che riporta a 137 byte .
— Arnauld,

2

Buccia , 15 byte

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

Provalo online!

Forza bruta, molto lenta.

Spiegazione

ḟ§Ë#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).

impossibile ottenere risultati
— asmgx

@asmgx Il programma è davvero lento. Sembra andare in timeout su TIO per input di lunghezza 8 o più, perché uccide il calcolo dopo 1 minuto. L'interprete offline dovrebbe dare un risultato se aspetti abbastanza a lungo (probabilmente diverse ore per input di lunghezza 10).
— Zgarb,

2

Perl 6 , 77 70 byte

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

Provalo online!

Adottando l'approccio di GB di inserire un personaggio fino a quando tutti i caratteri compaiono lo stesso numero di volte. Riceve una stringa che viene modificata sul posto.

Se i trattini bassi possono essere trattati come lettere, il regex può diventare /\w/, salvando due byte.

Spiegazione

{
                    .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 Sembra che il tuo miglioramento si basi sulla vecchia versione prima che io scoprissi il {*}trucco.
— nwellnhof,

Quindi è come una scorciatoia, .value(s)vero? Potrei dover aggiornare alcune delle mie vecchie soluzioni
— Jo King,


1

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

Flag del compilatore -DF=;for(i=0;b[i];i++ -DB=b[i](29 byte)

Aggiunto supporto per case miste.

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

Provalo online!


1

Pyth, 31 30 byte

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

Provalo qui

Spiegazione

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 byte

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
}

Provalo online!


0

Kotlin Android, 413 byte

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

Prova online

Spiegazione passaggio 1 -> Seleziona un elenco di caratteri distinti. passo 2 -> Ottieni il conteggio di ogni carattere nella stringa e seleziona la frequenza massima del carattere. passaggio 3 -> ottenere la differenza di frequenza dei caratteri rispetto alla frequenza massima dei caratteri passo 4 -> posizionare i caratteri rispetto alle posizioni nella stringa. Buona risoluzione!



0

PHP ,185 173 170 byte

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

Provalo online!

Ungolfed (e non ternario e non ottimizzato).

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