Quine에 고양이 2 마리


30

도전

동일한 언어의 고양이 프로그램 인 A와 B의 두 프로그램을 만드십시오. 연결될 때, AB (동일한 언어로도)는 quine이어야합니다.

예를 들어, 가정 helloworld언어 XYZ 모두 고양이 프로그램입니다. 해당 helloworld언어로 된 퀴즈 인 경우 솔루션이 유효합니다.

고양이와 quines에 익숙하지 않은 사람들을 위해, 고양이 프로그램은 stdin을 통해 주어진 것을 정확하게 인쇄하는 프로그램이며 quine은 자체 소스 코드를 인쇄하는 프로그램입니다.

채점 및 규칙

  • 연결된 AB 프로그램의 총 바이트 수는 점수입니다. 이것이 코드 골프이기 때문에 가장 낮은 점수가 이깁니다.
  • 표준 허점은 금지되어 있습니다
  • 입력은 stdin에서 가져와야하고 출력은 stdout으로 이동해야합니다.
  • 고양이 프로그램은 논쟁을 할 필요가 없습니다. 그들은 stdin을 stdout에 복사하기 만하면됩니다.
  • 퀴는 프로그램에 입력이 없을 때 작동하지만 다른 입력에 대해서는 올바르게 작동하지 않아도됩니다.
  • quine은 소스 코드를 정확히 한 번만 인쇄하면 더 이상 종료 할 필요가 없습니다.
  • quine은 1 바이트 이상이어야합니다.
  • A와 B는 같은 프로그램 일 수 있습니다.
  • BA는 퀴네 또는 유효한 프로그램 일 필요는 없습니다.

나는 당신이 A와 B가 같은 프로그램 규칙이 될 수 있다고 생각하지 않습니다
Muhammad Salman

2
@MuhammadSalman 저의 원래 아이디어는 고양이 프로그램을 두 배로 만들어서 키 네로 바꾸는 것이 었습니다. 나는 그것이 가능한지 완전히 확신하지 못했기 때문에 더 쉬운 솔루션의 문을 열고 싶었습니다. 내가 두 가지 모두 잘못 알고있는 것처럼 보이지만 괜찮습니다.
Beefster

3
AB많은 언어에 0 바이트 고양이가 0 바이트 퀴를 허용하므로 비어 있지 않아야 함을 추가 해야합니다.
DJMcMayhem

9
@DJMcMayhem 0 바이트 quine은 유효한 quine이 아닙니다.
Nissa

4
고양이 프로그램이란 무엇입니까?
Pedro A

답변:


32

V , 2 + 2 == 4 바이트

2i2i

quine을보십시오!

고양이를보십시오!

A2i

B2i

어떻게 작동합니까?

먼저 V의 작동 방식에 대한 설명입니다. 이 대답을 가능하게하는 한 가지 주목할만한 점은 V에서 빈 프로그램 고양이 프로그램이라는 것입니다. 이것은 특별한 경우가 아니며 V 작동 방식에 내재되어 있습니다. 시작시 모든 입력이 "버퍼"로로드되고 각 명령이 어쨌든 버퍼를 수정 한 다음 프로그램이 완료되면 버퍼가 암시 적으로 인쇄됩니다. 이것은 모든 NOP 문자열이 고양이 프로그램이라는 것을 의미합니다.

i명령 수단은 모드 삽입 입력 다음의 모든 문자 수단 i버퍼에 추가 될 것이다. 앞에 숫자가 있으면 해당 텍스트가 n 번 복제 됩니다.

이는 cat 프로그램의 경우 버퍼에 아무것도 추가되지 않으며 읽은대로 인쇄됨을 의미합니다. 다른 말로:

        " (Implicitly) Load all input
2       " 2 times,
 i      " Insert the following text into the buffer...
        " (nothing)
        " (Implicitly) Print the buffer

그러나 quine의 경우 i: 뒤에 텍스트가 있습니다 .

2       " 2 times,
 i      " Insert the following text into the buffer...
  2i    "   "2i"
        " (Implicitly) Print the buffer

건방진 대답

V , 0 바이트

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

A 는 빈 프로그램입니다.

B 는 또한 빈 프로그램입니다.

:피


21
다른 모든 언어 : Oy, 우리는 막 다른 길을 쳤다! . V : * 포스트 표준 quine * .
Outgolfer Erik

13

루비, 71 바이트

2;puts (<<2*2+?2)[/.+2/m]||$<.read
2;puts (<<2*2+?2)[/.+2/m]||$<.read
2

다음과 같이 고양이로 나눌 수 있습니다.

2;puts (<<2*2+?2)[/.+2/m]||$<.read
2

;puts (<<2*2+?2)[/.+2/m]||$<.read
2

두 고양이는 앞의 2 개를 제외하고는 동일하며, 이는 3 가지 프로그램 모두에서 전혀 작동하지 않습니다. 이것은 <<2herestring입니다. 즉, 자체 줄에서 종료 2가 될 때까지 다음 줄에서 시작하는 모든 것이 문자열이며, 우리는 자신을 연결 *2하고 후행 2를 추가합니다. 고양이에서 herestring은 잘 구성되어 있지만 비어 있습니다. 정규식이 일치하지 않으므로 $<.read식과 출력 STDOUT으로 넘어갑니다 . 일단 고양이를 연결하면 문자열은 세 번째 줄까지 끝나지 않으므로 정규 표현식이 일치하고 단락을 출력하고 퀴인을 출력합니다.


11

Pyth, 29 바이트 (5 + 24) 27 바이트 (5 + 22)

pz=T0?TzjN*2]"pz=T0?TzjN*2]     # Quine
pz=T0                           # Cat A
     ?TzjN*2]"pz=T0?TzjN*2]     # Cat B

재미있었습니다.
여기에 quine을
보십시오 여기 에 첫 번째 고양이를 보십시오 여기 에 두 번째 고양이를
보십시오

설명

Cat A
pz=T0
pz       Print the input.
  =T0    (Irrelevant for cat)

Cat B
?TzjN*2]"pz=T0?TzjN*2]
?Tz                      If T (10) is truthy, output the input.
   jN*2]"pz=T0?TzjN*2]   (Irrelevant for cat)

Quine
pz=T0?TzjN*2]"pz=T0?TzjN*2]
pz                            Print the (empty) input (without a newline).
  =T0                         Set T to 0.
     ?Tz                      If T (0) is truthy, output the input.
             "pz=T0?TzjN*2]   Otherwise, get this string...
          *2]                 ... take two copies...
        jN                    ... and join them with a quote.

11

C # (Visual C # 컴파일러) 551 바이트

A : 95 바이트

class A{public static int i=2;static void Main(string[]args){System.Console.Write(args[0]);}}//

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

B : 438 + 18 바이트

class A{public static int i=0;}
class B{static void Main(string[]args){if(A.i<1){System.Console.Write(args[0]);return;}var a=@"class A{{public static int i=2;static void Main(string[]args){{System.Console.Write(args[0]);}}}}//class A{{public static int i=0;}}
class B{{static void Main(string[]args){{if(A.i<1){{System.Console.Write(args[0]);return;}}var a=@{0}{1}{0};System.Console.Write(a,'{0}',a);}}}}";System.Console.Write(a,'"',a);}}

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

A + B : 533 + 18 바이트

class A{public static int i=2;static void Main(string[]args){System.Console.Write(args[0]);}}//class A{public static int i=0;}
class B{static void Main(string[]args){if(A.i<1){System.Console.Write(args[0]);return;}var a=@"class A{{public static int i=2;static void Main(string[]args){{System.Console.Write(args[0]);}}}}//class A{{public static int i=0;}}
class B{{static void Main(string[]args){{if(A.i<1){{System.Console.Write(args[0]);return;}}var a=@{0}{1}{0};System.Console.Write(a,'{0}',a);}}}}";System.Console.Write(a,'"',a);}}

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

A와 B는 명령 줄 인수로 입력을받습니다. A + B는 모든 입력을 무시합니다. /p:StartupObject=BMSBuild에 전송 된 옵션 에 대해 B 및 A + B의 18 바이트가 추가됩니다 . A + B에서만 엄격하게 필요하지만 B에도없는 것은 부정 행위처럼 보입니다.이 방법으로 A + B의 컴파일러 플래그는 A (없음)의 컴파일러 플래그와 B의 컴파일러 플래그입니다.

설명

프로그램 A는 간단합니다. 클래스 A는로 i초기화 된 (사용하지 않은) 정적 변수를 포함하며 2실행될 때 첫 번째 인수를 인쇄합니다. //끝은 A + B 코드에 대한 중요하지만, 그 자체로 아무것도하지 않는다.

프로그램 B는 격리 상 이상하지만 본질적으로 동일합니다. 로 i초기화 된 정적 변수를 포함하는 클래스 A를 생성 한 0다음 클래스 B의 Main 메서드를 실행합니다.이 메서드는 A.i1보다 작기 때문에 프로그램 A와 동일 하며 이상한 것들보다 먼저 반환됩니다. 줄 바꿈은 여기서 필요하지 않지만 A + B에는 중요합니다.

From //프로그램 A를 결합하면 프로그램 B의 클래스 A 선언을 주석 처리하지만, 줄 바꿈으로 인해 클래스 B가 양호하므로 대신 프로그램 A A.i2값 을 참조 할 수 있습니다. 컴파일러 플래그는 A.Main ()도 존재하므로 프로그램을 B.Main ()으로 실행합니다. 결과적으로 Program A + B는 인수를 출력하지 않고 대신 기본적으로 표준 C # quine 인 B.Main ()의 다음 세그먼트로 이동 합니다.


1
"고양이 프로그램은 stdin을 stdout에 복사해야한다"
Jakob

9

하스켈 , 116 + 20 = 187 175 174 136 바이트

Ørjan Johansen이 보여준 이후 많은 바이트가 절약되었습니다. interact

고양이 1

g=";main|idmain<-(++\"g=\"++show g++g)=interact idmain|1>0=interact id";main|idmain<-(++"g="++show g++g)=interact id

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

고양이 2

main|1>0=interact id

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

g=";main|idmain<-(++\"g=\"++show g++g)=interact idmain|1>0=interact id";main|idmain<-(++"g="++show g++g)=interact idmain|1>0=interact id

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


여기서 기본 원리는 두 번째 고양이를 첫 번째 고양이에 추가 할 때 상호 작용하는 함수의 이름을에서로 변경 a한다는 것 idmain입니다. interact id고양이 이기 때문에 idmainquine을 반환하는 함수가 필요합니다. 확실한 해결책은을 사용하는 const것이지만 입력이 비어 있다고 가정 할 수 있기 때문에 (++)작동합니다. 여기에서 우리는 꽤 표준적인 수단을 통해 소스 코드를 찾고, 소스 g를 인코딩 하는 변수 를 가지고 있으며 특수 래퍼를 사용하여 문자열 형태와 코드 형태로 인쇄합니다. 엔코더를 맨 앞에 두어야하는 예외가 interact id있습니다. 이것은 여분의 것을 의미합니다g=인코딩되지 않았으며 수동으로 처리해야합니다. 다음 고양이는 다른 고양이의 끝에 붙일 때 유효한 코드를 작성해야하기 때문에 꽤 표준입니다. 따라서 두 고양이 모두 패턴 가드의 인스턴스가되어야합니다.

대체 전략, 43 + 105 = 186 (148)

고양이 1

g="";main|idmain<-(++g++show g)=interact id

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

고양이 2

main|1>0=interact id where g="g=\"\";main|idmain<-(++g++show g)=interact idmain|1>0=interact id where g="

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

g="";main|idmain<-(++g++show g)=interact idmain|1>0=interact id where g="g=\"\";main|idmain<-(++g++show g)=interact idmain|1>0=interact id where g="

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


1
getContents+ putStr를 로 바꾸면 상당히 단축 할 수 있습니다 interact id. 온라인으로 사용해보십시오! (Quine은 더 이상 비어 있지 않은 입력과 함께 작동하지 않으므로에 대한 (++ ...)섹션을 사용할 수 있습니다 idmain.)
Ørjan Johansen

@ ØrjanJohansen 감사합니다! 에 대해 몰랐습니다 interact. Haskell로 IO 작업을 거의하지 않기 때문입니다. 게시물을 수정했습니다.
밀 마법사

8

파이썬 3, 286 바이트

나의 첫번째 파이썬 골프와 나의 첫번째 quine! 매우 우아하지는 않지만 작동합니다.

프로그램 A (238 바이트)

from atexit import*;s="from atexit import*;s=%r;register(lambda:print(end='b'in globals()and s%%s or open(0).read()));b=0\nif's'not in vars():print(end=open(0).read())";register(lambda:print(end='b'in globals()and s%s or open(0).read()));

(후행 줄 바꿈 없음)

프로그램 B (48 바이트)

b=0
if's'not in vars():print(end=open(0).read())

(후행 줄 바꿈 없음)

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

감사의 말

  • Jo King 덕분에 -24 바이트
  • Jo King 덕분에 -82 바이트

줄 바꿈과 따옴표를 end=open...사용할 필요없이 %r대신 사용할 수 있습니다%s
Jo King

쿨로 전환했습니다 %r. 그래도 개행에 대해 무슨 뜻인지 확실하지 않습니다.
Jakob

1
%s개행을 형식화하는 대신 리터럴 만하면 \n됩니다. 또한 자체 줄에 있어야하는 것을 제외하고 ;문을 분할 하는 데 사용할 수도 있습니다 . 를 수행하여 문자열에서 이스케이프 할 수 있습니다 . 문자열 형식을 지정하는 데 필요한 유일한 인수는 문자열 자체이며 다른 모든 항목은 스트라이핑 할 수 있습니다.\nif%%%
Jo King

1
프로그램 B (및 텍스트)는 locals()2 바이트를 절약 하는 데 사용할 수 있습니다 .
Jonathan Allan

6

C ++ (클랑) , 313 + 102 = 415 바이트

프로그램 A (개행으로 끝남) :

#include<cstdio>
#define Q(x,y)#x,B=#y;x
int c;auto I="#include<cstdio>",A=Q(int main(){if(c)printf("%s\n#define Q(x,y)#x\",\"#y;x\nint c;auto I=\"%s\",A=Q(%s,)\n#ifdef Q\nint n=++c;\n#else\n%s\n%s\n#endif",I,I,A,I,B);else while((c=getchar())>=0)putchar(c);},int c;int main(){while((c=getchar())>=0)putchar(c);})

프로그램 B (개행으로 끝나지 않음) :

#ifdef Q
int n=++c;
#else
#include<cstdio>
int c;int main(){while((c=getchar())>=0)putchar(c);}
#endif

끔찍하게 몰래 나오지 않으며 평소와 같이 C ++은 Quining에 그렇게 좋지 않습니다. 바이트를 깎는 방법이 있고 같은 생각에서 벗어나더라도 놀라지 않을 것입니다. 하나의 작은 캐치가 정의 된 후에 무언가의 동작을 변경하고 있으며 부작용이있는 동적 변수 이니셜 라이저가 트릭을 수행합니다. (컴파일러 확장이없는 C 에서도이 작업을 수행 할 수 있습니까?)

온라인으로 사용해보십시오 : A , B , AB

(내가 아는 유일한 이식성 문제는 프로그램 <cstdio>이 전역 네임 스페이스와std .)


5

베 펀지 -98 (FBBI) , 8 + 15 = 23 바이트

A + B : (입력이없는 경우에만 작동)

+9*5~,#@#@~,9j>:#,_:@#"

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

에이:

+9*5~,#@

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

비:

#@~,9j>:#,_:@#"

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


누군가가 송곳니 답변을 관리할지 궁금합니다. 이건 2D가 아닌 것이 나쁘다 :-/
Beefster

@Beefster yeah. The problem is it’s pretty hard to do a 2d Quine. Maybe I’ll work on something though
MildlyMilquetoast

5

Python 3, 100 + 37 = 137 bytes

Program A:

s='s=%r;print(end=open(0).read())#print(end=open(0).read())\nprint(s%%s)';print(end=open(0).read())#

Try it online!

Program B:

print(end=open(0).read())
print(s%s)

Try it online!

Make Quine AB

s='s=%r;print(end=open(0).read())#print(end=open(0).read())\nprint(s%%s)';print(end=open(0).read())#print(end=open(0).read())
print(s%s)

Try it online!

Only works when input is empty, otherwise it prepends the input to the output.


The double quotes should be single ones.
Jonathan Allan

Crashing is allowed?
Jakob

@Jakob The question doesn't say that crashing is not allowed, and typically output to STDERR is ignored
Jo King

Ok, fair enough. Clever shortcuts!
Jakob

4

Attache, 15 + 126 = 141 bytes

A:

AllInput[]|Echo

Try it online!

B:

@{If[_,s.="AllInput[]|Echo@{If[_,s.=%s;;Printf[s,Repr!s],AllInput[]|Echo]es}|Call";;Printf[s,Repr!s],AllInput[]|Echo]es}|Call

Try it online!

A + B:

AllInput[]|Echo@{If[_,s.="AllInput[]|Echo@{If[_,s.=%s;;Printf[s,Repr!s],AllInput[]|Echo]es}|Call";;Printf[s,Repr!s],AllInput[]|Echo]es}|Call

Try it online!

Explanation

Each of the cat program encodes AllInput[]|Echo, which is a simple cat program. B is the main quine phase; alone, it is a vectorized function (through unary @) called with no inputs (being called as |Call). Thus, the first conditional If[_,A,B] executes B, which is simply AllInput[]|Echo.

When A + B is executed, unary @ becomes binary @ due to Echo merging with the lambda:

AllInput[]|Echo@{If[_, ...

Now, this means that the lambda is executed before Echo is. Back to the conditional, this function now has all of STDIN as an argument. So, If[_,A,B] executes A, which is the standard quine framework.


3

Stax, 16 + 12 = 28 bytes

Cat 1:

"yi|d|ca34b4lr"y

Run and debug it

"yi|d|ca34b4lr"y Full program, implicit input
"yi|d|ca34b4lr"  Push the string
               y Push raw input
                 Implicit output of top item

Cat 2:

i|d|ca34b4lr

Run and debug it

i|d|ca34b4lr Full program, implicit input
i            Don't parse input (prefix directive)
 |d          Push main stack depth, always zero
   |c        Cancel because top item is falsy, and implicitly print
     a34b4lr Never executed

Quine:

"yi|d|ca34b4lr"yi|d|ca34b4lr

Run and debug it

"yi|d|ca34b4lr"yi|d|ca34b4lr Full program
"yi|d|ca34b4lr"              Push the string
               y             Push input
                i            No-op
                 |d          Push main stack depth, i.e. 2
                   |c        Do nothing because top is truthy
                     a       Get the string to the top
                      34     Push 34 (charcode of ")
                        b    Copy both
                         4l  Listify top 4
                           r Reverse
                             Implicit output

3

Cat 1 :

Lua, 41 bytes

a=io.read;while a(0)do io.write(a(1))end;

Try it online!


Cat 2 :

Lua, 70 bytes

if a then io.input(arg[0])end;a=io.read;while a(0)do io.write(a(1))end

Try it online!


Quine :

Lua, 111 bytes

a=io.read;while a(0)do io.write(a(1))end
if a then io.input(arg[0])end;a=io.read;while a(0)do io.write(a(1))end

Try it online!

io.input(arg[0]) in Cat 2 sets the current file as standard input, and as a result, the cat prints the source code


1
Welcome to PPCG
Muhammad Salman

You can save one byte in cat 1 by removing the last semi-colon ?
Muhammad Salman

1
Unfortunately, reading the current file is a standard loophole. But nice try anyway.
Beefster


0

JavaScript (Node.js), 199 bytes


a=()=>console.log(require('fs').readFileSync(0)+'');a();var a=a||0;b=()=>console.log(require('fs').readFileSync(0)+'');!a?b():c=()=>console.log(`a=${a};a();var a=a||0;b=${b};!a?b():c=${c},c()`),c()

Try it online!

Cat A, 57 bytes


a=()=>console.log(require('fs').readFileSync(0)+'');a();

Try it online!

Cat B, 142 bytes

var a=a||0;b=()=>console.log(require('fs').readFileSync(0)+'');!a?b():c=()=>console.log(`a=${a};a();var a=a||0;b=${b};!a?b():c=${c},c()`),c()

Try it online!

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