Huruf nomor yang sama


19

Surat-surat dari kata-kata itu menginginkan keadilan.

Mereka memutuskan untuk tampil beberapa kali dalam kalimat yang sama.

Contoh:

Priorities

Akan menjadi:

Ppprrioooritttieeesss

Setiap huruf muncul 3 kali, seperti huruf yang paling umum i, muncul 3 kali.

Tidak masalah di mana Anda meletakkan huruf-huruf yang diulang, asalkan di sebelah huruf yang sama.

Yaitu:

Pppriooorritttieeesss tidak apa-apa (huruf 'r')

Ppprioororitttieeesss tidak baik (huruf 'r')

Contoh lain:

invoice

Akan menjadi:

innvvooiccee

Contoh lain:

Remittance Advice

Akan menjadi:

Rrremmmiitttaannncce Adddvvvice

Spasi, koma, tanda tanya, kutipan, dll. Tidak dianggap sebagai huruf untuk tantangan ini. Hanya perlu mempertimbangkan [a-zA-Z]. Sekali ruang saja sudah cukup, dan urutan hurufnya harus tetap sama.

Kapitalisasi huruf tidak menjadi masalah, huruf besar dan kecil dihitung sebagai huruf yang sama. Yaitu: Pipmemiliki 2 'P's dan 1' I ', sehingga akan menjadi Piip.

Ini adalah huruf yang tidak sensitif jika dalam bentuk apa pun, Piip=piip=piiP=PiiP

Ini adalah


2
Mungkin saya sarankan menggunakan Sandbox untuk tantangan masa depan untuk membantu menyelesaikan semua detail sebelum memposting pertanyaan ke utama
Jo King

Apakah "rrreeemmmiiitttaaannncccdddvvv" merupakan output yang dapat diterima dalam contoh yang diberikan (karena urutan huruf yang berbeda (sebagaimana didefinisikan sebagai az) masih dipertahankan)? (Jawaban Jeli saya saat ini bergantung pada penafsiran ini sebagai OK.)
Jonathan Allan

1
@ JonathanAllan Hmm, meskipun saya meninggalkan pilihan untuk OP, saya sangat meragukannya. Bukan saja karakter non-huruf (spasi) hilang, tetapi Anda juga meletakkan semua karakter di samping satu sama lain alih-alih menyimpannya di tempat yang sama. Output Anda membuat tantangan berbeda dan lebih mudah (imho).
Kevin Cruijssen

1
@KevinCruijssen ruang di sebelah kiri - bukan surat maka tidak perlu mematuhi "dan urutan surat harus tetap sama"
Jonathan Allan

1
@ Jonathan Allan Ah, tidak memperhatikan ruang, salahku. Saya benar-benar memahami alasan yang Anda berikan dalam jawaban Jelly Anda dan berdasarkan itu memang merupakan output yang valid, tetapi saya lebih suka melihat frasa berubah, kemudian membiarkan output Anda, karena itu akan benar-benar mengubah tantangan itu sendiri.
Kevin Cruijssen

Jawaban:


5

05AB1E , 16 byte

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

Cobalah online!

Penjelasan

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

Cobalah online!

Pendekatan Basis:

  • mencuri beberapa ide dari @ J.Apakah pendekatan R + stringr , saya menyelamatkan 26 byte!
  • 5 byte lainnya disimpan menggunakan @ J.Apakah saran untuk penyalahgunaan +operator R.

Saya terkesan Anda harus 111 dengan base-R!
J.Oke

@ J. Aduh: Setelah menerbitkan solusi 137 byte asli saya, saya sedikit mengubah pendekatan saya yang terinspirasi oleh Anda, dan pada dasarnya saya menyatu dengan solusi Anda, hanya dengan menghapus stringr: D
digEmAll

1
106 byte dengan penyalahgunaan operator. Base-R menang!
Joe

@ J. Aduh: luar biasa!
digEmAll

5

Perl 6 , 82 byte

-3 byte terima kasih kepada nwellnhof

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

Cobalah online!

Mengambil string yang bisa berubah dan memodifikasinya.

Penjelasan:

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

Anda dapat membuat rantai .=seperti operator a.=lc.=subst(...). Saya tidak yakin apakah mengubah huruf yang ada diperbolehkan. Juga <:L>bukannya <:Ll>.
nwellnhof

@nwellnhof Ya, penanya mengatakan bahwa keluarannya tidak peka huruf besar-kecil
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))

Cobalah online!

Berkomentar

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

Keterampilan saya JS mengisap, jadi aku sedikit bingung tentang bagian ini: o[l] = // updates o[l] to a non-numeric value. Jika saya mengerti benar, oapakah integer-array di dalam Fdan gfungsinya, tetapi berubah menjadi string-array yang menahan satu atau lebih kali karakter cpada bagian yang saya sebutkan sebelumnya? Juga, saya kira nilai-nilai osecara undefineddefault, karena Anda menggunakan o[l]=-~o[l]bukan ++o[l]?
Kevin Cruijssen

1
@KevinCruijssen Kami ingin setiap huruf diisi hingga jumlah maksimum kejadian hanya sekali. Dengan memperbarui o[l]ke huruf, setiap iterasi selanjutnya dengan huruf yang sama akan mengarah ke m - o[l] --> NaN(bilangan minus huruf) dan l.repeat(NaN) == ''. (Tentang poin terakhir: ya, itu benar.)
Arnauld

Ah ok, terima kasih atas penjelasannya! :)
Kevin Cruijssen

(dan saya seharusnya mengatakan string daripada surat )
Arnauld

5

J , 33 56 46 byte

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

Cobalah online!

Tidak dapat menemukan cara untuk menghindari penggunaan ~:tolower dua kali.

Bagaimana itu bekerja

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

Saya tidak terlalu pandai stringr. Mengembalikan campuran huruf besar dan kecil karena pertanyaannya mengatakan itu tidak masalah.

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}

Cobalah online!

Penjelasan

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

Larutan:

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

Contoh:

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"

Penjelasan:

Mungkin golf dengan pendekatan yang berbeda, akan terus berpikir

{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

Arang , 33 32 byte

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

Cobalah online! Tautan adalah untuk mengucapkan versi kode. Penjelasan:

  θ                                 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 berkat @Nevay .

Output dalam huruf besar penuh.

Cobalah online. (CATATAN: String.repeat(int)ditiru sebagairepeat(String,int) untuk byte-count yang sama, karena Java 11 belum pada TIO.)

Penjelasan:

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

Bisakah Anda menggunakan var untuk byte?
Quintec

@ Quintec Alih-alih charmaksud Anda? Sayangnya tidak ada. varhanya dapat digunakan untuk bidang tunggal. Jadi, bukannya char m=1,i=127,a[]=new char[i];itu var m=1;var i=127;var a=new char[i];. Berikut tip berguna tentang apa yang dapat dan tidak bisa Anda lakukan dengan Java 10's var. (Saya bisa mengganti intdalam loop dengan var, tetapi byte-count akan tetap sama.)
Kevin Cruijssen

Gotcha, terima kasih. Masih tidak tahu bagaimana Java 9/10/11 bekerja, haha, saya akan tetap pada 8; p
Quintec

@ Quintec Java 9 Saya juga tidak begitu mengerti, karena terutama berfokus pada REPL itu. Java 10 sebagian besar sama dengan Java 8, kecuali untuk var. Dan Java 11 nyaris tidak memiliki perubahan sama sekali terkait codegolf, kecuali untuk String.repeatmetode yang sudah saya gunakan berkali-kali. Ini juga memiliki yang baru String.stripLeadingatau String.stripTrailing, yang bertindak seperti trimtetapi hanya spasi putih terkemuka / tertinggal, dan String.isBlank()yang sama dengan String.trim().isEmpty()(kosong atau hanya spasi putih).
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 dari @ETHproductions

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

Mencoba menjelaskan

;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

Cobalah online!


1
Semoga Anda tidak keberatan, saya memperluas bagian dari penjelasan (bahwa satu baris yang menjelaskan apa yang dilakukan sekitar 10 karakter sekaligus: P) úTriknya adalah jenius, btw :-)
ETHproductions

@ ETHproductions Saya menghargainya. Saya tidak terlalu pandai berbahasa Inggris jadi terima kasih
Luis felipe De jesus Munoz

1
Sayangnya, tampaknya gagal ketika ada non-huruf yang terlibat (tidak boleh diubah). Perbaikan sederhana adalah dengan memasukkan ñ oC ó¥, meskipun perlu menambahkan kembali ke ;...
ETHproduksi

Tunggu ... sejak kapan ñbekerja pada string ?! @ ETHproductions, tolong katakan padaku itu tambahan baru-baru ini dan aku belum menghadapinya selama ini!
Shaggy

@Shaggy Rupanya 2,5 bulan yang lalu - tapi jangan khawatir, bahkan saya sudah lupa sampai ada jawaban ini ;-)
ETHproduksi

2

Ruby , 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}

Cobalah online!

Saya mencoba pendekatan yang berbeda, tetapi apa yang benar-benar menghemat banyak byte adalah menambahkan satu karakter setiap kali.

Bagaimana:

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

Ini menggunakan rentang char 'a'..'z'. Lihat skrip untuk Powershell sebelumnya di bawah ini.

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

Script tes yang dijelaskan:

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

Keluaran:

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

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

Cobalah online!

Solusi yang sangat panjang ...

Penjelasan:

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

Cobalah online!

+33 byte dari solusi pertama saya untuk kendala-kendala tambahan yang tidak pernah berakhir. JS payah di manipulasi string case-insensitive lho.

-3 byte kembali Terima kasih @Arnauld.

Penjelasan

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

Solusi harus mampu menangani input kasus campuran.
Shaggy

@ Shaggy Saya pikir tantangannya telah diedit setelah komentar Anda. Sepertinya kasus output tidak masalah.
Arnauld

Di sisi lain, fungsi harus dapat digunakan kembali , yang tidak terjadi di sini.
Arnauld

@Arnauld Oh kadang-kadang saya melihat Anda menggunakan fs sebagai penyimpanan sementara jadi saya pikir tidak apa
Shieru Asakoto

map()fungsi panggilan balik aman digunakan untuk penyimpanan, karena fungsi itu didefinisikan dalam lingkup lokal. Menggunakan fungsi utama - yang didefinisikan secara global - lebih berbahaya. Di sini, Anda dapat menggunakan panggilan balik yang pertama map(), yang membawa Anda kembali ke 137 byte .
Arnauld

2

Sekam , 15 byte

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

Cobalah online!

Brute force, jadi sangat lambat.

Penjelasan

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

tidak bisa mendapatkan hasil sama sekali
asmgx

@asmgx Program ini sangat lambat. Tampaknya time out pada TIO untuk input dengan panjang 8 dan lebih lama, karena membunuh perhitungan setelah 1 menit. Penerjemah offline harus memberikan hasil jika Anda menunggu cukup lama (mungkin beberapa jam untuk panjang-10 input).
Zgarb

2

Perl 6 , 77 70 byte

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

Cobalah online!

Mengambil pendekatan GB memasukkan karakter sampai semua karakter muncul jumlah yang sama kali. Menerima string yang dimodifikasi di tempat.

Jika garis bawah dapat diperlakukan seperti huruf, regex bisa menjadi /\w/ , menghemat dua byte.

Penjelasan

{
                    .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 Sepertinya peningkatan Anda didasarkan pada versi lama sebelum saya menemukan {*}triknya.
nwellnhof

Jadi itu seperti jalan pintas untuk .value(s)itu? Rapi, saya mungkin harus memperbarui beberapa solusi lama saya
Jo King


1

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

Bendera penyusun -DF=;for(i=0;b[i];i++ -DB=b[i] (29 byte)

Menambahkan dukungan case campuran.

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

Cobalah online!


1

Pyth, 31 30 byte

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

Coba di sini

Penjelasan

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

Tidak disatukan

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
}

Cobalah online!


0

Android Kotlin, 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])}}

Coba online

Penjelasan langkah 1 -> Pilih daftar karakter yang berbeda. langkah 2 -> Dapatkan hitung setiap karakter dalam string dan pilih frekuensi karakter maks. langkah 3 -> dapatkan perbedaan frekuensi karakter sehubungan dengan frekuensi maksimum karakter langkah 4 -> tempat karakter terkait dengan posisi dalam string. Selamat Memecahkan!



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

Cobalah online!

Tidak disatukan (dan tidak ternaried dan tidak dioptimalkan).

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; 
}
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.