Munge la mia password


17

Le parole comuni dovrebbero essere comunque evitate per essere utilizzate come password. Questa sfida è di circa la codifica di un programma molto semplice che munges una determinata password ( M difica U ino N OT G uessed E asily).

Ingresso

Una parola, che è una stringa scritta nell'alfabeto abcdefghijklmnopqrstuvwxyz. Non importa se le lettere sono minuscole o maiuscole.

munging

  1. Cambia ogni sequenza ripetuta di una stessa lettera in se stessa preceduta dal numero di volte in cui la lettera è stata ripetuta ( LLLLcon 4L)
  2. Cambia il primo acon@
  3. Cambia il primo bcon8
  4. Cambia il primo ccon(
  5. Cambia il primo dcon6
  6. Cambia il primo econ3
  7. Cambia il primo fcon#
  8. Cambia il primo gcon9
  9. Cambia il primo hcon#
  10. Cambia il primo icon1
  11. Cambia il secondo icon!
  12. Cambia il primo kcon<
  13. Cambia il primo lcon1
  14. Cambia il secondo lconi
  15. Cambia il primo ocon0
  16. Cambia il primo qcon9
  17. Cambia il primo scon5
  18. Cambia il secondo scon$
  19. Cambia il primo tcon+
  20. Cambia il primo vcon>
  21. Cambia il secondo vcon<
  22. Cambia il primo wconuu
  23. Cambia il secondo wcon2u
  24. Cambia il primo xcon%
  25. Cambia il primo ycon?

La regola 1 deve essere applicata il numero di volte necessario fino a quando non è possibile applicarla di più. Successivamente vengono applicate le altre regole.

Output La parola munged

Esempi

  • codegolf -> (0639o1#
  • programming -> pr09r@2m1ng
  • puzzles -> pu2z135
  • passwords -> p@25uu0r6$
  • wwww -> 4uu
  • aaaaaaaaaaa -> 11a
  • lllolllolll -> 3103io3l
  • jjjmjjjj -> 3jm4j

Questo è , quindi per favore rendi il tuo programma il più breve possibile!

Nulla in questo post dovrebbe essere usato come idee per le password o come parte delle pratiche relative alle password.


18
Il fatto stesso che programmi come questo siano possibili significa che l'attaccante potrebbe scriverli e truffare la password (e provare i vari munges) altrettanto facilmente (ancora più facile perché spesso hanno accesso a hardware migliore). Quindi, per motivi di sicurezza, dirò: nulla in questo post dovrebbe essere usato come idee per le password o come parte delle pratiche relative alle password.
NH.

1
Raccomando di rendere audace quel disclaimer e di duplicarlo in alto. Non puoi mai stare troppo attento ...
wizzwizz4,

Risposte:


11

Java 8, 237 321 319 280 247 241 240 237 byte

s->{for(int a[]=new int[26],i=0,l=s.length,t,x;i<l;i+=t){for(t=0;++t+i<l&&s[i]==s[t+i];);System.out.print((t>1?t+"":"")+(++a[x=s[i]-65]>2?s[i]:"@8(63#9#1J<1MN0P9R5+U>u%?ZABCDEFGH!JKiMNOPQR$TU<2XYZ".charAt(x+26*~-a[x])+(x==22?"u":"")));}}

+84 byte perché le regole hanno subito modifiche .. ( EDIT: finalmente tornando ai miei 237 byte iniziali. ) Sostituire WWWWcon 222Wè facile in Java, ma con 4Wno. Se solo Java avesse un modo di usare il gruppo di acquisizione regex per qualcosa. Ottenere la lunghezza con "$1".length(), sostituire la corrispondenza stessa con "$1".replace(...), convertire la corrispondenza in un numero intero new Integer("$1")o usare qualcosa di simile come Retina (ie s.replaceAll("(?=(.)\\1)(\\1)+","$#2$1")) o JavaScript (ie s.replaceAll("(.)\\1+",m->m.length()+m.charAt(0))) sarebbe la mia cosa numero 1 che mi piacerebbe vedere in Java nella futuro a beneficio del codegolfing ..>.> Penso che questa sia la decima + volta che odio Java non può fare nulla con la partita del gruppo di acquisizione ..
-78 byte grazie a @ OlivierGrégoire .

L'I / O è maiuscolo.

Spiegazione:

Provalo qui.

s->{                           // Method with String parameter and no return-type
  for(int a[]=new int[26],     //  Array with 26x 0
          i=0,                 //  Index-integer, starting at 0
          l=s.length,          //  Length
          t,x;                 //  Temp integers
      i<l;                     //  Loop (1) over the characters of the input
      i+=t){                   //    After every iteration: Increase `i` by `t`
    for(t=0;++                 //   Reset `t` to 1
        t+i<l                  //   Inner loop (2) from `t+i` to `l` (exclusive)
        &&s[i]==s[t+i];        //   as long as the `i`'th and `t+i`'th characters are equal
    );                         //   End of inner loop (2)
    System.out.print(          //   Print:
     (t>1?t+"":"")             //    If `t` is larger than 1: print `t`
     +(++a[x=s[i]-65]>2?       //    +If the current character occurs for the third time:
       s[i]                    //      Simply print the character
      :                        //     Else:
       "@8(63#9#1J<1MN0P9R5+U>u%?ZABCDEFGH!JKiMNOPQR$TU<2XYZ".charAt(x
                               //      Print the converted character at position `x`
        +26*~-a[x])            //       + 26 if it's the second time occurring
       +(x==22?"u":"")));      //      And also print an additional "u" if it's 'W'
  }                            //  End of loop (1)
}                              // End of method

10

JavaScript (ES6), 147 byte

s=>[[/(.)\1+/g,m=>m.length+m[0]],..."a@b8c(d6e3f#g9h#i1k<l1o0q9s5t+v>x%y?i!lis$v<".match(/../g),["w","uu"],["w","2u"]].map(r=>s=s.replace(...r))&&s

Casi test

Spiegazione

Esegue una serie di sostituzioni sulla stringa di input, snell'ordine specificato dalla sfida. Ogni elemento della serie è un array o una stringa, con due elementi, che viene quindi distribuito ( ...r) e passato a s.replace().

s=>[
    [/(.)\1+/g, m=>m.length + m[0]],// first replacement: transform repeated letters
                                    // into run-length encoding

                                    // string split into length-2 partitions and
                                    // spread into the main array
    ..."a@b8c(d6e3f#g9h#i1k<l1o0q9s5t+v>x%y?i!lis$v<".match(/../g),
                                    // next replacements: all single-char replacements.
                                    // "second" versions are placed at the end so they
                                    //    replace the second instance of that char

    ["w","uu"],["w","2u"]           // last replacements: the two "w" replacements
]
.map(r=> s = s.replace(...r))       // run all replacements, updating s as we go
&& s                                // and return the final string

Ottima risposta
mdahmoune,

6

05AB1E , 69 byte

-9 byte grazie a Emigna

γvygD≠×yÙ}J.•k®zĀÒĀ+ÎÍ=ëµι
•"@8(63#9#1<1095+>%?!i$<"ø'w„uu„2u‚â«vy`.;

Provalo online!


Puoi usare'w„uu„2u‚â
Emigna il

Per favore potresti verificare il risultato per wwww come input?
mdahmoune,

@mdahmoune Emette4uu
Okx il

@Emigna prodotto cartesiano, buona idea.
Okx,

La prima parte può essereγvygD≠×yÙ}J
Emigna,

6

Perl 5 , 152 + 1 ( -p) = 153 byte

s/(.)\1+/(length$&).$1/ge;%k='a@b8c(d6e3f#g9h#i1j!k<l1mio0q9r5s$t+u>v<x%y?'=~/./g;for$i(sort keys%k){$r=$k{$i};$i=~y/jmru/ilsv/;s/$i/$r/}s/w/uu/;s/w/2u/

Provalo online!


Perché cosa intendi con (-p)?
mdahmoune,

1
@mdahmoune -pè usato come argomento alla perlriga di comando che legge automaticamente input da STDINe prints il contenuto $_alla fine dello script. TIO consente tale opzione e poiché perl -pe<code>è 1 byte in più rispetto perl -e<code>a come viene conteggiato come un byte aggiuntivo.
Dom Hastings,

Credo che tu abbia fatto un errore di battitura, non dovrebbe il ~tra j~kessere un !posto? Attualmente ha sostituito la seconda occorrenza di icon ~invece di a !.
Kevin Cruijssen,

@Xcali #testingonproduction
NieDzejkob

2
@NieDzejkob Non c'è posto migliore. Questo è l'unico modo in cui sai che funzionerà in produzione.
Xcali,

4

Probabilmente non il più golfato potrebbe essere, ma funziona.

-6 byte grazie agli ovs

-77 byte grazie a NieDzejkob e Jonathan French

Python 3 , 329 323 byte 246 byte

import re;n=input()
for a in re.finditer('(\w)\\1+',n):b=a.group();n=n.replace(b,str(len(b))+b[0],1)
for A,B,C in[('abcdefghikloqstvxyw','@8(63#9#1<1095+>%?','uu'),('ilsvw','!i$<','2u')]:
	for a,b in zip(A,list(B)+[C]):n=n.replace(a,b,1)
print(n)

Provalo online!


1
Penso che potresti cadere.lower()
mdahmoune,

Ciò ha senso, non ero sicuro di dover gestire maiuscole o meno.
reffu,



2
In realtà, la tua risposta non funziona. jjjmjjjjdovrebbe emettere 3jm4jma uscite 3jm3jj. Modifica: 258 byte con questo problema risolto
NieDzejkob,

3

Retina , 166 124 byte

(.)\1+
$.&$1
([a-y])(?<!\1.+)
¶$&
¶w
uu
T`l¶`@8(63#9#1j<\1mn0\p9r5+u>\w%?_`¶.
([ilsvw])(?<!\1.+)
¶$&
¶w
2u
T`i\lsv¶`!i$<_`¶.

Provalo online! Spiegazione:

(.)\1+
$.&$1

Sostituisci una serie di lettere ripetute con la lunghezza e la lettera.

([a-y])(?<!\1.+)
¶$&

Abbina la prima occorrenza delle lettere aa ye contrassegnale con un segnaposto.

¶w
uu

Risolve la prima occorrenza di w.

T`l¶`@8(63#9#1j<\1mn0\p9r5+u>\w%?_`¶.

Correggi la prima occorrenza di tutte le altre lettere da aa yed elimina i segnaposto.

([ilsvw])(?<!\1.+)
¶$&

Segnare la (inizialmente) seconda occorrenza delle lettere i, l, s, v, o wcon un segnaposto.

¶w
2u

Risolve la seconda occorrenza di w.

T`i\lsv¶`!i$<_`¶.

Risolve la seconda occorrenza delle altre quattro lettere.


Pensi che sia possibile continuare a giocare a golf?
mdahmoune,

@mdahmoune Sì, penso di poter salvare 33 byte.
Neil,

Ho votato a favore della tua risposta :) sarà fantastico se salvi i 33 byte;)
mdahmoune,

@mdahmoune Buone notizie, in realtà ho salvato 42 byte!
Neil,

Ottimo, il tuo codice è il secondo più corto;)
mdahmoune,

3

Haskell , 221 218 213 byte

($(f<$>words"w2u li i! s$ v< a@ b8 c( d6 e3 f# g9 h# i1 k< l1 o0 q9 s5 t+ v> wuu x% y?")++[r]).foldr($)
f(a:b)(h:t)|a==h=b++t|1>0=h:f(a:b)t
f _ s=s
r(a:b)|(p,q)<-span(==a)b=[c|c<-show$1+length p,p>[]]++a:r q
r s=s

Provalo online!

Abusa di foldrfar passare la stringa attraverso una sequenza di trasformazioni di stringa all'indietro. La sequenza "inizia" con la rquale la sostituzione conta la ripetizione usando spanper spezzare la coda della corda quando smette di essere uguale alla testa. Se la prima parte non è vuota è una ripetizione, quindi stampiamo la lunghezza +1. Successivamente, esaminiamo un argomento fper ogni sostituzione del personaggio in ordine (inverso). I rimpiazzi sono codificati come una singola stringa con il primo carattere come carattere da sostituire e il resto come stringa (poiché i rimpiazzi w sono più caratteri) per andare al suo posto. Ho messo queste stringhe codificate in una grande stringa separata da spazi in modo chewords possa dividerla in un elenco per me.

EDIT: Grazie @Laikoni per avermi salvato 5 byte! Era un uso intelligente di $cui non avevo pensato. Inoltre non conoscevo quel <-trucco.


Grazie per una spiegazione dettagliata;)
mdahmoune,

1
Puoi usare al (p,q)<-span(==a)bposto di let(p,q)=span(==a)be p>[] invece di p/=[].
Laikoni,

2
Risparmia altri due byte rendendo minutile: ($(f<$>words"w2u ... y?")++[r]).foldr($) provalo online!
Laikoni,

2

Lua , 173 byte

s=...for c,r in("uua@b8c(d6e3f#g9h#i1i!jjk<l1limmnno0ppq9rrs5s$t+v>v<wuuw2ux%y?zz"):gmatch"(.)(.u?)"do s=s:gsub(c..c.."+",function(p)return#p..c end):gsub(c,r,1)end print(s)

Provalo online!

Ungolfed e spiegato:

s = ...


--This string contains every character to replace, followed by
--the character(s) it should be replaced with.
--
--It also contains all characters for which repeated sequences
--of them should be replaced by "<number><character>". That is,
--all letters in the alphabet. This way, a single loop can do
--both the "replace repeated characters" and "encode characters"
--operations, saving a for loop iterating over the alphabet.
--
--Characters that shouldn't be replaced will be replaced with
--themselves.
--
--In order to avoid matching half of the "replace u with u"
--command as the replace part of another command, "uu" is placed
--at the beginning of the string. This ensures that only the
--2-character replacements for "w" get an extra "u".

cmdstring = "uua@b8c(d6e3f#g9h#i1i!jjk<l1limmnno0ppq9rrs5s$t+v>v<wuuw2ux%y?zz"


--Iterate over all the search/replace commands.
--The character to replace is in the "c" variable, the string to
--replace it with is in "r".
--
--Due to the dummy search/replace commands (i.e. "mm") placed
--in the string, this loop will also iterate over all letters
--of the alphabet.

for c,r in cmdstring:gmatch("(.)(.u?)") do
	
	--First, replace any occurences of the current letter
	--multiple times in a row with "<number><letter>".
	s = s:gsub(c..c.."+", function(p)
		return #p .. c
	end)
	
	--Then, replace the first occurence of the letter
	--with the replacement from the command string.
	s = s:gsub(c, r, 1)
end

print(s)

Lol lua :) buon lavoro
mdahmoune,

2

C # (.NET Core), 317 , 289 , 279 byte

p=>{string r="",l=r,h=r,c="a@b8c(d6e3f#g9h#i1i!k<l1lio0q9s5s$t+v>v<wuw2x%y?";int i=0,n=p.Length,d,a=1;for(;i<n;i++){h=p[i]+"";if(h==p[(i==n-1?i:i+1)]+""&&i!=n-1)a++;else{d=c.IndexOf(h);if(d>=0&&d%2<1){l=c[d+1]+"";h=l=="u"?"uu":l;c=c.Remove(d,2);}r+=a>1?a+""+h:h;a=1;}}return r;};

Provalo online!

Spero sia giusto ricevere un array di caratteri come input e non come stringa.

Ungolfed :

string result = "", casesCharReplacement = result, currentChar = result, cases = "a@b8c(d6e3f#g9h#i1i!k<l1lio0q9s5s$t+v>v<wuw2x%y?";
int i = 0, n = pas.Length, casesIndex, charAmounts = 1;

// For every char in the pass.
for (; i < n; i++)
{
    currentChar = pas[i] + "";
    // if the next char is equal to the current and its not the end of the string then add a +1 to the repeated letter.
    if (currentChar == (pas[(i == n - 1 ? i : i + 1)] + "") && i != n - 1)
        charAmounts++;
    else
    {
        // Finished reading repeated chars (N+Char).
        casesIndex = cases.IndexOf(currentChar);
        // Look for the replacement character: only if the index is an even position, otherwise I could mess up with letters like 'i'.
        if (casesIndex >= 0 && casesIndex % 2 < 1)
        {
            casesCharReplacement = cases[casesIndex + 1]+"";
            // Add the **** +u
            currentChar = casesCharReplacement == "u"?"uu": casesCharReplacement;
            // Remove the 2 replacement characters (ex: a@) as I won't need them anymore.
            cases = cases.Remove(casesIndex, 2);
        }
        // if the amount of letters founded is =1 then only the letter, otherwise number and the letter already replaced with the cases.
        result += charAmounts > 1 ? charAmounts + ""+currentChar : currentChar;
        charAmounts = 1;
    }
}
return result;

1
Sì, va bene :) per l'input
mdahmoune,

2

C ++, 571 495 478 444 byte

-127 byte grazie a Zacharý

#include<string>
#define F r.find(
#define U(S,n)p=F s(S)+b[i]);if(p-size_t(-1)){b.replace(i,1,r.substr(p+n+1,F'/',n+p)-p-2));r.replace(p+1,F'/',p+1)-p,"");}
#define V(A)i<A.size();++i,c
using s=std::string;s m(s a){s b,r="/a@/b8/c(/d6/e3/f#/g9/h#/i1//i!/k</l1//li/o0/q9/s5//s$/t+/v>/wuu//w2u/x%/y?/";int c=1,i=0;for(;V(a)=1){for(;a[i]==a[i+1]&&1+V(a)++);b+=(c-1?std::to_string(c):"")+a[i];}for(i=0;V(b)){auto U("/",1)else{U("//",2)}}return b;}

la "/a@/b8/c(/d6/e3/f#/g9/h#/i1//i!/k</l1//li/o0/q9/s5//s$/t+/v>/wuu//w2u/x%/y?/"stringa viene utilizzata per trasformare da un carattere ad altri. 1 /significa che il primo "prossimo carattere" dovrebbe essere sostituito da quello che segue il successivo /, 2 significa che il secondo "prossimo carattere" dovrebbe essere sostituito da quanto segue.

Provalo online


Bene, potresti aggiungere un link tio.run?
mdahmoune,

È stato aggiunto il link TIO di @mdahmoune, con il codice da testare per i casi di test :)
HatsuPointerKun

494 byte e aggiorna il collegamento TIO di conseguenza se lo cambi.
Zacharý,

@ Zacharý Devi inserire uno spazio tra il nome della macro e il contenuto della macro, altrimenti genera un errore durante la compilazione con C ++ 17. Sai anche come eliminare un collegamento TIO? (dal momento che il vecchio è inutile)
HatsuPointerKun


2

R , 224 219 byte

function(s,K=function(x)el(strsplit(x,"")),u=rle(K(s)))
Reduce(function(x,y)sub(K('abcdefghiiklloqsstvvwwxy')[y],c(K('@8(63#9#1!<1i095$+><'),'uu','2u',K('%?'))[y],x),1:24,paste0(gsub("1","",paste(u$l)),u$v,collapse=""))

Provalo online!

Cattivo, ma la parte principale è la sostituzione iterativa in Reduce. subcambia solo la prima occorrenza della partita.

Grazie a JayCe per aver segnalato un bel golf!


Ottimo lavoro :)))))
mdahmoune,

salva 1 byte riorganizzando args. Non fa una grande differenza, lo so;)
JayCe

@JayCe Ho trovato qualche byte in più :-)
Giuseppe

1

Perl 5 , 123 byte

122 byte codice + 1 per -p.

Sviluppata indipendentemente da @ Xcali 's risposta , ma utilizzando un processo molto simile.

s/(.)\1+/$&=~y!!!c.$1/ge;eval"s/$1/$2/"while'a@b8c(d6e3f#g9h#i1i!k<l1lio0q9s5t+v>v<x%y?'=~/(.)(.)/g;s/s/\$/;s/w/uu/;s;w;2u

Provalo online!


1

Python 2 , 220 216 194 190 188 188 byte

import re
S=re.sub(r'(.)\1+',lambda m:`len(m.group(0))`+m.group(1),input())
for a,b in zip('abcdefghiiklloqsstvvxyww',list('@8(63#9#1!<1i095$+><%?')+['uu','2u']):S=S.replace(a,b,1)
print S

Provalo online!

Python 3 , 187 byte

import re
S=re.sub(r'(.)\1+',lambda m:str(len(m.group(0)))+m.group(1),input())
for a,b in zip('abcdefghiiklloqsstvvxyww',[*'@8(63#9#1!<1i095$+><%?','uu','2u']):S=S.replace(a,b,1)
print(S)

Provalo online!


Thanx Tfeld 192 byte tio.run/…
mdahmoune,

Grande golf;)
mdahmoune,

186 byte . Puoi anche portarlo facilmente su Python 3 in 192 byte , ma non credo che dovrebbe essere una risposta separata.
NieDzejkob,

@NieDzejkob Sembra che la tua versione Python 2 golfizzata produca un output diverso rispetto alla versione corrente dell'OP o alla tua versione Python 3.
Jonathan Frech,

@JomathanFrech dispiace, come sempre test sulla produzione. 188 byte
NieDzejkob il

1

Pip , 103 102 byte

aR:`(.)\1+`#_.B
Fm"abcdefghiiklloqsstvvwwxy"Z"@8(63#9#1!<1i095$+><WU%?"I#Ya@?@maRA:ym@1aR'W"uu"R'U"2u"

Provalo online!

Spiegazione

Il codice esegue tre passaggi di trasformazione:

aR:`(.)\1+`#_.B  Process runs of identical letters

a                1st cmdline argument
 R:              Do this replacement and assign back to a:
   `(.)\1+`       This regex (matches 2 or more of same character in a row)
           #_.B   Replace with callback function: concatenate (length of full match) and
                  (first capture group)
                  Note: #_.B is a shortcut form for {#a.b}

Fm"..."Z"..."I#Ya@?@maRA:ym@1  Do the bulk of rules 2-25

  "..."                        String of letters to replace
       Z"..."                  Zip with string of characters to replace with
Fm                             For each m in the zipped list:
                   @m           First item of m is letter to replace
                a@?             Find its index in a, or nil if it isn't in a
               Y                Yank that into y
             I#                 If len of that is truthy:*
                     aRA:        Replace character in a at...
                         y        index y...
                          m@1     with second item of m

aR'W"uu"R'U"2u"  Clean up substitution
                 In the previous step, the replacements each had to be a single character.
                 This doesn't work for uu and 2u, so we use W and U instead (safe, since
                 uppercase letters won't be in the input) and replace them here with the
                 correct substitutions.
aR'W"uu"         In a, replace W with uu
        R'U"2u"  and U with 2u
                 and print the result (implicit)

* Dobbiamo verificare se a@?m@0è zero. Non è sufficiente verificare che sia vero, poiché 0 è un indice legittimo che è falso. Pip non ha un modo breve per testare se un valore è zero, ma testare la sua lunghezza funziona abbastanza bene in questo caso: qualsiasi numero avrà lunghezza almeno 1 (verità), e zero ha lunghezza pari a zero (falsità).

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.