비밀번호를 뮤지


17

일반적인 단어는 여전히 암호로 사용하지 않아야합니다. 이 문제는 munges가 주어진 암호 (있는 매우 간단한 프로그램을 코딩에 관한 M odify U ntil N OT G는 uessed E를 asily).

입력

알파벳으로 쓰여진 문자열 인 단어입니다 abcdefghijklmnopqrstuvwxyz. 글자가 소문자인지 대문자인지는 중요하지 않습니다.

문징

  1. 동일의 반복 서열의 변화 편지 편지가 반복 횟수가 선행 자체를 ( LLLL4L)
  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

자바 (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 바이트 때문에 규칙이 변경 .. 가지고 : 마지막으로 다시 내 초기 237 바이트. 편집을 교체) WWWW222W쉽게 자바에서, 그러나와 4W하지 .. 단지 자바 뭔가 정규식 캡처 그룹을 사용하는 방법이 있다면. 로 길이를 "$1".length()얻거나, 일치 자체를으로 바꾸거나 "$1".replace(...), 일치를 정수로 변환 new Integer("$1")하거나, Retina (ie s.replaceAll("(?=(.)\\1)(\\1)+","$#2$1")) 또는 JavaScript (ie s.replaceAll("(.)\\1+",m->m.length()+m.charAt(0)))와 비슷한 것을 사용하면 Java에서보고 싶은 숫자 1이 될 것입니다. codegolfing의 혜택을 누릴 미래 ..>.> Java가 캡처 그룹 일치로 아무것도 할 수없는 10 번째 시간이라고 생각합니다 . @ OlivierGrégoire
덕분에 -78 바이트 .

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

자바 스크립트 (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 바이트

Emigna 덕분에 -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 Cartesian 제품, 좋은 생각입니다.
Okx

첫 번째 부분은 다음과 같습니다.γvygD≠×yÙ}J
Emigna

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자동 입력을 판독 커맨드에서 STDINprint내용 S는 $_스크립트의 끝에. TIO는 해당 옵션을 허용하며, 추가 바이트로 계산 된 perl -pe<code>것보다 1 바이트가 더 많기 때문에 perl -e<code>.
Dom Hastings

나는 당신이 오타를 만들었다 고 생각합니다. 그 ~사이 j~k!대신 해서는 안 됩니까? 이것은 현재의 두 번째 발생을 대체 i로모그래퍼 ~대신의 !.
Kevin Cruijssen '10

@Xcali #testingonproduction
NieDzejkob

2
@NieDzejkob 더 좋은 곳은 없습니다. 그것이 프로덕션 환경에서 작동한다는 것을 아는 유일한 방법입니다.
Xcali

4

아마도 가장 골프가 될 수는 없지만 작동합니다.

ovs 덕분에 -6 바이트

NieDzejkob 및 Jonathan French 덕분에 -77 바이트

파이썬 3 , 329323 바이트 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()
mdahmoune

대문자를 처리해야하는지 여부는 확실하지 않습니다.
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%?_`¶.

에서 다른 모든 문자의 첫 번째 항목을 수정 ay하고 자리 표시자를 삭제합니다.

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

문자의 (원래) 번째 발생을 마크 i, l, s, v, 또는 w플레이스 홀더와.

¶w
2u

의 두 번째 발생을 수정하십시오 w.

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

다른 네 글자의 두 번째 항목을 수정하십시오.


더 골프를 치는 것이 가능하다고 생각하십니까?
mdahmoune

@ mdahmoune 예, 33 바이트를 절약 할 수 있다고 생각합니다.
Neil

나는 당신의 대답을 투표했습니다 :) 만약 당신이 33 바이트를 저장한다면 그것은 좋을 것입니다;)
mdahmoune

@mdahmoune 좋은 소식, 실제로 42 바이트를 절약했습니다!
Neil

좋아요, 코드는 두 번째로 짧습니다;)
mdahmoune

3

하스켈 , 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넣으면 목록으로 나눌 수 있습니다.

편집 : 5 바이트를 절약 해 주셔서 감사합니다 @Laikoni! 그것은 $내가 생각하지 못한 영리한 사용법 이었습니다. 나도 그 <-트릭을 몰랐다 .


자세한 설명은
감사합니다

1
(p,q)<-span(==a)b대신 let(p,q)=span(==a)bp>[] 대신에 사용할 수 있습니다 p/=[].
Laikoni

2
mpointfree 를 만들어서 2 바이트를 더 절약하십시오 : ($(f<$>words"w2u ... y?")++[r]).foldr($) 온라인으로 사용해보십시오!
Laikoni

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 :) good job
mdahmoune

2

C # (. NET 코어), 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 바이트

Zacharý 덕분에 -127 바이트

#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 링크가 추가되었습니다. :)
HatsuPointerKun

494 바이트 이며 TIO 링크를 변경하면 이에 따라 업데이트하십시오.
Zacharý

@ Zacharý 매크로 이름과 매크로 내용 사이에 공백을 넣어야합니다. 그렇지 않으면 C ++ 17로 컴파일 할 때 오류가 발생합니다. 또한 TIO 링크를 삭제하는 방법을 알고 있습니까? (오래된 것은 쓸모가 없기 때문에)
HatsuPointerKun


2

R , 224 219 바이트

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

온라인으로 사용해보십시오!

불쾌하지만, 주요 부분은의 반복 치환입니다 Reduce. sub일치하는 첫 번째 항목 만 변경합니다.

좋은 골프를 지적 해준 JayCe에게 감사드립니다!


Good job :)))))
mdahmoune

args를 재 배열하여 1 바이트를 절약하십시오. 내가 아는 큰 차이는 없습니다;)
JayCe

@JayCe 나는 더 많은 바이트를 발견했다 :-)
Giuseppe


1

파이썬 (2) , 220 (216) 194 190 188 바이트

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

온라인으로 사용해보십시오!

파이썬 3 , 187 바이트

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)

온라인으로 사용해보십시오!


Thanx Tfeld 192 바이트 tio.run/…
mdahmoune

그레이트 골프;)
mdahmoune

186 바이트 . 이것을 192 바이트 로 Python 3에 쉽게 이식 할 수는 있지만 별도의 대답이어야한다고 생각하지 않습니다.
NieDzejkob

@NieDzejkob 골프를 친 Python 2 버전이 OP의 현재 버전 또는 Python 3 버전과 다른 출력을 생성하는 것처럼 보입니다.
조나단 프레 치

항상 프로덕션에서 테스트하는 것처럼 @JomathanFrech 죄송합니다. 188 바이트
NieDzejkob

1

, 103 102 바이트

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

온라인으로 사용해보십시오!

설명

코드는 3 단계의 변환을 수행합니다.

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)

* 우리 a@?m@0는 nil 인지 테스트해야합니다 . 0은 거짓 인 합법적 인 색인이므로 사실인지 테스트하는 것만으로는 충분하지 않습니다. Pip에는 값이 nil인지 테스트하는 간단한 기본 방법이 없지만이 경우 길이를 테스트하면 충분합니다. 모든 숫자의 길이는 1 이상 (truthy)이고 nil은 nil (falsey)입니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.