Замкніть мій пароль


17

Загальні слова все ж слід уникати, щоб вони використовувались як паролі. Це завдання про кодування дуже проста програма , яка munges даний пароль ( M odify U ntil N ВЗ G uessed E asily).

Вхідні дані

Слово, яке є рядком, записаним в алфавіті abcdefghijklmnopqrstuvwxyz. Не має значення, чи букви букви малі чи великі.

Зміна

  1. Змініть будь-яку повторювану послідовність тієї самої літери до себе, перед якою кількість повторень букви ( LLLLз 4L)
  2. Змініть перший aна@
  3. Змініть перший bна8
  4. Змініть перший cна(
  5. Змініть перший dна6
  6. Змініть перший eна3
  7. Змініть перший fна#
  8. Змініть перший gна9
  9. Змініть перший hна#
  10. Змініть перший iна1
  11. Змініть другий iна!
  12. Змініть перший kна<
  13. Змініть перший lна1
  14. Змініть другий lнаi
  15. Змініть перший oна0
  16. Змініть перший qна9
  17. Змініть перший sна5
  18. Змініть другий sна$
  19. Змініть перший tна+
  20. Змініть перший vна>
  21. Змініть другий vна<
  22. Змініть перший wнаuu
  23. Змініть другий wна2u
  24. Змініть перший xна%
  25. Змініть перший yна?

Правило 1 потрібно застосовувати необхідну кількість разів, поки не вдасться застосувати його більше. Після цього застосовуються решта правил.

Вихідні слова

Приклади

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

Це , тому будь ласка, зробіть свою програму якомога коротшою!

Ніщо в цій публікації не повинно використовуватися як ідеї щодо паролів або як будь-яка частина парольних практик.


18
Сам факт, що такі програми можливі, означає, що зловмисник міг написати їх і зв'язати пароль (і спробувати різні мюнджери) так само легко (ще простіше, оскільки вони часто мають доступ до кращого обладнання). Тож задля безпеки я скажу: нічого в цій публікації не слід використовувати як ідеї щодо паролів або як будь-яка частина парольних практик.
NH.

1
Я рекомендую зробити цю відмову жирною і дублювати її вгорі. Ви ніколи не можете бути занадто обережними ...
wizzwizz4

Відповіді:


11

Java 8, 237 321 319 280 247 241 240 237 байт

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 байт , тому що правила є зміни .. ( EDIT :. Нарешті назад в моїх початкових 237 байт ) Заміна WWWWз 222Wлегко в Java, але 4Wнемає .. Якщо тільки Java був спосіб використовувати регулярний вираз захоплення-групи для чого - то. Отримати довжину на "$1".length(), замінити сам матч на "$1".replace(...), перетворити матч на ціле число new Integer("$1"), або використовувати щось подібне, як Retina (тобто s.replaceAll("(?=(.)\\1)(\\1)+","$#2$1")) або JavaScript (тобто s.replaceAll("(.)\\1+",m->m.length()+m.charAt(0))) - це моя річ номер 1, яку я хотів би бачити в Java Майбутнє виграє кодогельфінг ..>.> Я думаю, що це вже 10-й + час, коли я ненавиджу Java, нічого не можу зробити з матчем групи захоплення ..
-78 байт завдяки @ OlivierGrégoire .

I / O - це великі регістри.

Пояснення:

Спробуйте тут.

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 байт

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

Випробування

Пояснення

Виконує серію замін у вхідному рядку s, у порядку, визначеному викликом. Кожен елемент серії є масивом або рядком з двома елементами, який потім поширюється ( ...r) та передається в 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

Дуже хороша відповідь
mdahmoune

6

05AB1E , 69 байт

-9 байт завдяки Еміньї

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

Спробуйте в Інтернеті!


Ви можете скористатися'w„uu„2u‚â
Emigna

Plz, ви можете перевірити результат для wwww як вхід?
mdahmoune

@mdahmoune Виходить4uu
Okx

@Emigna декартовий продукт, хороша ідея.
Okx

Першою частиною може бутиγvygD≠×yÙ}J
Емінья

6

Perl 5 , 152 + 1 ( -p) = 153 байти

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/

Спробуйте в Інтернеті!


Plz, що ви маєте на увазі під (-p)?
mdahmoune

1
@mdahmoune -pвикористовується як аргумент для perlв командному рядку, який автоматично зчитує вхід із STDINта prints вмісту $_в кінці сценарію. TIO дозволяє цей параметр, і оскільки perl -pe<code>на 1 байт більше, ніж perl -e<code>він вважається одним додатковим байтом.
Дом Гастінгс

Я думаю, що ти зробив помилку на помилку, чи не слід ~між ними j~kбути !? В даний час він замінив другий входження iз ~замість !.
Кевін Кройсейсен

@Xcali #testingonproduction
NieDzejkob

2
@NieDzejkob Немає кращого місця. Це єдиний спосіб, коли ви знаєте, що це буде працювати у виробництві.
Xcali

4

Напевно, не самий гольф, який він може бути, але це працює.

-6 байт завдяки ов

-77 байт завдяки НієДжейкобу та Джонатану Французу

Python 3 , 329 323 байт 246 байт

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)

Спробуйте в Інтернеті!


1
Я думаю, ти .lower()
можеш кинутись

Це має сенс, я не був впевнений, потрібно мені обробляти великі регістри чи ні.
reffu



2
Насправді ваша відповідь не працює. jjjmjjjjповинен виводити, 3jm4jале виводити 3jm3jj. Редагувати: Виправлено 258 байт із цією проблемою
NieDzejkob

3

Сітківка , 166 124 байт

(.)\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$<_`¶.

Спробуйте в Інтернеті! Пояснення:

(.)\1+
$.&$1

Замініть пробіг повторних літер на довжину та букву.

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

Зіставте перші букви букв aдо yта позначте їх заповнювачем.

¶w
uu

Виправте перше виникнення w.

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

Закріпити перше входження всіх інших букв від aдо yі видалити наповнювачі.

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

Марк (спочатку) друге входження букв i, l, s, v, або wз заповнювачем.

¶w
2u

Виправте друге виникнення w.

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

Виправте друге виникнення інших чотирьох літер.


Як ви вважаєте, чи можна додатково пограти в гольф?
mdahmoune

@mdahmoune Так, я думаю, що я можу зберегти 33 байти.
Ніл

Я підкреслив вашу відповідь :) буде чудово, якщо ви збережете 33 байти;)
mdahmoune

@mdahmoune Хороша новина, я фактично врятував 42 байти!
Ніл


3

Haskell , 221 218 213 байт

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

Спробуйте в Інтернеті!

Зловживає foldrзапускати рядок через послідовність перетворень рядків назад. Послідовність "починається", з rякої проводиться заміна підрахунку повторів, використовуючи spanдля розриву хвоста струни, коли вона перестає дорівнювати голові. Якщо перша частина цього не порожня, це повторення, тому ми друкуємо довжину +1. Далі ми вкажемо аргумент на fкожну заміну символів у (зворотному) порядку. Заміни кодуються як один рядок, першим символом є символ, який потрібно замінити, а решта як рядок (оскільки w заміни є декількома символами), щоб перейти на своє місце. Я розміщую ці закодовані рядки в одну велику рядок, розділену пробілами, щоб wordsпереламати її на список для мене.

EDIT: Дякую @Laikoni, що врятував мені 5 байт! Це було розумне використання, про яке $я не думав. Я також не знав цієї <-хитрості.


Спасибі за детальне пояснення;)
mdahmoune

1
Ви можете використовувати (p,q)<-span(==a)bзамість let(p,q)=span(==a)bі p>[] замість p/=[].
Laikoni

2
Збережіть ще два байти, зробивши mpointfree: ($(f<$>words"w2u ... y?")++[r]).foldr($) Спробуйте це онлайн!
Лайконі

2

Луа , 173 байт

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)

Спробуйте в Інтернеті!

Необурений і пояснив:

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 :) хороша робота
mdahmoune

2

C # (.NET Core), 317 , 289 , 279 байт

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

Спробуйте в Інтернеті!

Я сподіваюся, що нормально отримувати масив char як вхідний, а не рядок.

Безголівки :

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
Так, це нормально :) для введення
mdahmoune

2

C ++, 571 495 478 444 байт

-127 байт завдяки 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;}

"/a@/b8/c(/d6/e3/f#/g9/h#/i1//i!/k</l1//li/o0/q9/s5//s$/t+/v>/wuu//w2u/x%/y?/"рядок використовується для перетворення з одного символу іншим. 1 /означає, що перший "наступний знак" слід замінити тим, що слідує за наступним /, 2 означає, що другий "наступний знак" повинен бути замінений на наступне.

Спробуйте в Інтернеті


Чудово, ви можете додати посилання tio.run?
mdahmoune

@mdahmoune TIO link is added, with the code to test for your test cases :)
HatsuPointerKun

494 bytes, and update the TIO link accordingly if you change it.
Zacharý

@Zacharý You need to put a space between the macro name and the macro content, otherwise, it throws an error when compiling with C++ 17. Also, do you know how to delete a TIO link ? ( since the old one is useless )
HatsuPointerKun


2

R, 224 219 bytes

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

Try it online!

Nasty, but the main part is the iterative substitution in the Reduce. sub changes only the first occurrence of the match.

Thanks to JayCe for pointing out a nice golf!


Good job :)))))
mdahmoune

save 1 byte by rearranging args. Doesn't make a huge difference I know ;)
JayCe

@JayCe I found some more bytes :-)
Giuseppe

1

Perl 5, 123 bytes

122 bytes code + 1 for -p.

Developed independently from @Xcali's answer, but using a very similar process.

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

Try it online!


1

Python 2, 220 216 194 190 188 bytes

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

Try it online!

Python 3, 187 bytes

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)

Try it online!


Thanx Tfeld 192 bytes tio.run/…
mdahmoune

Great golfing ;)
mdahmoune

186 bytes. You can also easily port this to Python 3 in 192 bytes, but I don't think it should be a separate answer.
NieDzejkob

@NieDzejkob It seems as though your golfed Python 2 version produces a different output than the OP's current version or your Python 3 version.
Jonathan Frech

@JomathanFrech sorry, as always testing on production. 188 bytes
NieDzejkob

1

Pip, 103 102 bytes

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

Try it online!

Explanation

The code does three steps of transformation:

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)

* We need to test whether a@?m@0 is nil. It's not enough to test that it's truthy, since 0 is a legitimate index that is falsey. Pip doesn't have a short builtin way to test if a value is nil, but testing its length works well enough in this case: any number will have length at least 1 (truthy), and nil has length of nil (falsey).

Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.