예를 들어 통역사를 만드십시오!


10

예는 공백으로 구분 된 몇 가지 지침 이있는 스택 기반 언어 입니다.

yes: Push 1 to the stack
no: Push 0 to the stack
what: Push the input to the stack (input is taken at the start of program execution and is the same for the whole execution)
sure: Increment the last item in the stack
nah: Decrement the last item in the stack
really: If the last stack item is a number, replace it with its Unicode character. If it is a letter, replace it with its Unicode char code.
oh: convert the stack to strings and concatenate it, and push that to the stack.
nope: remove the first stack item
yep: remove the last stack item

스택의 마지막 요소는 항상 프로그램 끝에서 출력됩니다. 영숫자가 아닌 문자와 공백이 아닌 문자는 모두 무시됩니다. 모든 코드는 소문자입니다. 예제 프로그램 :

yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
oh

인쇄합니다 Hello, World!.

what

입력을 인쇄합니다 ( cat프로그램).

no nah

인쇄합니다 -1.

no really

NUL문자를 인쇄합니다 ( U+0000)

what 
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really 
oh

입력과 밑줄을 인쇄합니다.

yes no nope

인쇄물 0

yes no yep

인쇄합니다 1.

가능한 적은 바이트로 인터프리터를 작성해야합니다. 다음은 JS 구현입니다 (골프가 아님).

function yes(code, input){
	var stack = [];
	var functions = {
		"yes": "stack.push(1)",
		"no": "stack.push(0)",
		"what": "stack.push(input)",
		"sure": "stack[stack.length - 1] ++",
		"nah": "stack[stack.length - 1] --",
		"really": "stack[stack.length - 1] = (typeof lastItem === 'number' ? String.fromCharCode(lastItem) : lastItem.charCodeAt())",
		"oh": "stack.push(stack.reduce((x, y)=>''+x+y))",
		"nope": "stack.shift()",
		"yep": "stack.pop()"
	};
	code.replace(/[^a-z ]/g, "").split(" ").map(x=>(lastItem = stack[stack.length - 1],eval(functions[x])));
	return stack[stack.length - 1];
}
textarea{
  display: block;
}
Code: <textarea id = "code"></textarea>
Input: <textarea id = "input"></textarea>
<button onclick = "output.value = yes(code.value, input.value)">Run</button>
<textarea id = "output"></textarea>

아래의 JS 답변 도 참조하십시오 .

관련된 모든 정수가 126보다 작거나 같고 really스택 상단에 다중 문자 문자열로 실행되지 않으며 스택이 100 요소보다 길지 않다고 가정 할 수 있습니다.

가장자리 케이스

  • yes yes oh인쇄합니다 11.
  • 입력은 문자열 또는 숫자 일 수 있습니다.
  • 코드는 모든 문자를 포함 할 수 있습니다. 일치하지 않는 [a-z ]것은 무시해야합니다.

1
테스트 케이스에 모든 명령이 포함되어 있는지 확인하십시오.
Leaky Nun

2
어떤 유형의 정수를 사용해야합니까? 오버플로가 있습니까? really스택 위에 다중 문자 문자열이 있으면 어떻게 합니까?
마틴 엔더

1
@ programmer5000 yes yes oh인쇄 하지 않아야 11합니까?
user41805

1
입력에 can 문자 만 포함되어 있다고 가정해도 괜찮 [a-zA-Z ]습니까?
user41805

1
입력 푸시 숫자를 입력 할 수 있습니까? 배열? Chars? 줄? 그렇다면 입력 문자열이 여러 줄이 될 수 있습니까? 스택의 마지막 항목 증분 마지막 항목이 숫자가 아닌 경우 어떻게합니까?
Luis Mendo

답변:


4

05AB1E , 77 67 63 61 바이트

Að«Ã#vyÇO§}ðý•9ǝ×н}ÀÀÙ™Íð•650в"X ¾ I > < DdiçëÇ} J r\r \"#:.V

프로그램이 스택 맨 위에 있다고 가정합니다.

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


모든 입력이 유효하다고 가정 할 수 있습니까? 예를 들어 프로그램을받을 수없는 경우yes no sey yep
Emigna

@Emigna 이것에 대한 테스트 사례가없고, 사양이 없으며, 누군가가 의견을 남긴 후에도 OP가이를 명확히하지 못했습니다.
Okx

테스트 사례가 부족하다는 것을 알았습니다. 이것에 대한 의견에서 아무것도 보지 못했기 때문에 그의 참조 프로그램이 유효하지 않은 명령을 무시하고 문자 코드의 합계가 유효한 명령과 일치하면 유효한 명령으로 실행할 수 있습니다.
Emigna

9

자바 스크립트 (ES6) 218 215 204 203 바이트

프로그램 문자열 s과 입력 i을 카레 구문으로 가져옵니다 (s)(i).

s=>i=>s.replace(/\w+/g,S=>(c=eval("[P()];P()+1;[s.shift()];1;0;s=[s.join``];P()-1;i;P()[0]?k.charCodeAt():String.fromCharCode(k)".split`;`[parseInt(S,35)%156%9])).map||s.push(c),s=[],P=_=>k=s.pop())&&P()

어떻게?

완벽한 해시 함수 parseInt(S, 35) % 156 % 9를 사용하여 명령어 S0… 8 의 인덱스로 변환 하고이 인덱스를 사용하여 실행할 JS 코드를 선택합니다.

instruction | base 35 -> dec. | % 156 | % 9 | JS code
------------+-----------------+-------+-----+---------------------------------------------
"yes"       |           42168 |    48 |   3 | 1
"no"        |             829 |    49 |   4 | 0
"what"      |         1393204 |   124 |   7 | i
"sure"      |         1238209 |    37 |   1 | P()+1
"nah"       |           28542 |   150 |   6 | P()-1
"really"    |      1439554619 |    35 |   8 | P()[0]?k.charCodeAt():String.fromCharCode(k)
"oh"        |             857 |    77 |   5 | s=[s.join``]
"nope"      |         1016414 |    74 |   2 | [s.shift()]
"yep"       |           42165 |    45 |   0 | [P()]

P의 기능은 스택 오프 마지막 항목을 팝업 에로드를 K .

.map () 메서드가 정의되어 있는지, 즉 결과가 배열인지 테스트하여 일부 명령어의 결과가 스택으로 푸시되지 않도록합니다 . 오에 대한 코드 는 의도적으로 배열을 반환하고 있으며 nopeyep도 배열을 반환 하도록 강요 합니다. 따라서 구문은 다음과 같습니다.

(c = eval("[code0];code1;...".split`;`[index])).map || s.push(c)

테스트 사례


5

로다 , 256 바이트

f c,n{s=[];(c/`\W|_`)()|{|m|s+=#m-2 if[m=~"yes|no"];s[-1]+=#m*2-7 if[m=~"sure|nah"];s+=n if[m="what"];s=s[#m%3:#s-#m%2]if[m=~"nope|yep"];{s+=""s()|s[-1].=_}if[m="oh"];{t=s[-1]y=t..""a=t+0;a=a..""{s[-1]=ord(s)}if[#a>#y]else{s[-1]=chr(t)}}if[#m=6]}_;[s[-1]]}

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

설명

#variable길이를 반환합니다 variable(문자열 또는 배열 인 경우).

f c,n{                         /*declare a function f with arguments c and n*/
s=[];                          /*initialise the stack*/
(c/`\W|_`)                     /*split the code on anything not [a-zA-Z0-9]*/
          ()|                  /*and push each of its values to the stream*/
{|m|...}_                      /*for each element m in the stream, do:*/
s+=#m-2 if[m=~"yes|no"];       /* add 1 or 0 to the stack if m is "yes" or "no"*/
s[-1]+=#m*2-7if[m=~"sure|nah"];/* increment or decrement the top element if m is "sure" or "nah"*/
s+=n if[m="what"];             /* push input if m is "what"*/
s=s[#m%3:#s-#m%2]              /* remove the first or last element of the stack
  if[m=~"nope|yep"];           /* if m is "nope" or "yep" */
{                 }if[m="oh"]; /* if m is "oh" do:*/
 s+=""                         /*  add an element to the stack*/
      s()|s[-1].=_             /*  for each element in s, concatenate that amount to the last element of the stack*/
{                   }if[#m=6]  /* if m is "really" (it's length is 6) do:*/
 t=s[-1]y=t..""                /*  get the last element of the stack*/
 a=t+0;a=a..""                 /*  add 0 to it, if a is a number, this does nothing, otherwise this makes a longer by 1 character*/
 {s[-1]=ord(s)}if[#a>#y]       /*  if a is longer than t (the last element is a char/string) replace it with its code point*/
 else{s[-1]=chr(t)}            /*  otherwise, replace the last element with the char it represents*/
 [s[-1]]                       /*finally output the top of the stack*/

3

Pyth , 69 바이트

Vczd=Y.v@c"+YsY X_1Y1 +Yw  +Y0 X_1Y_1    PY   +Y1 tY +PYCeY"d%CN23;eY

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


"Hello, World"프로그램에서 작동하지 않는 것 같습니다.
Okx

@Okx 그것은 작동한다; 링크에서 프로그램을 변경했습니다. 원래 프로그램이 너무 깁니다.
Leaky Nun

또는 그 문제에 대한 다른 많은 프로그램. 013456789yes 012345678no oh0을 인쇄하고 예상 출력은 10입니다.
Okx

또한 가장자리 yes yes oh질문 (문제에 지정된)에서는 작동하지 않으며 예상 출력은 11입니다.
Okx

@Okx 의견을보십시오. OP는이를 구체적으로 정의되지 않은 동작으로 지정했습니다.
Leaky Nun

1

JS (ES6) 361 340 바이트

c=>i=>(s=[],r="s[s.length-1]",c.replace(/[^a-z ]/g,"").split` `.map(x=>(eval({"yes":"s.push(1)","no":"s.push(0)","what":"s.push(i)","sure":"~++","nah":"~--","really":"~=((typeof ~)[0]<'o'?String.fromCharCode(~):lastItem.charCodeAt())","oh":"s.push(s.reduce((x,y)=>''+x+y))","nope":"s.shift()","yep":"s.pop()"}[x].replace(/~/g,r)))),eval(r))

카레를 통해 코드와 입력을받습니다.

var yes = 
c=>i=>(s=[],r="s[s.length-1]",c.replace(/[^a-z ]/g,"").split` `.map(x=>(eval({"yes":"s.push(1)","no":"s.push(0)","what":"s.push(i)","sure":"~++","nah":"~--","really":"~=((typeof ~)[0]<'o'?String.fromCharCode(~):lastItem.charCodeAt())","oh":"s.push(s.reduce((x,y)=>''+x+y))","nope":"s.shift()","yep":"s.pop()"}[x].replace(/~/g,r)))),eval(r))
textarea{
  display: block;
}
Code: <textarea id = "code"></textarea>
Input: <textarea id = "input"></textarea>
<button onclick = "output.value = yes(code.value)(input.value)">Run</button>
<textarea id = "output"></textarea>


1

자바 스크립트 (ES6) 220 216 바이트

c=>i=>c.replace(/\w+/g,x=>a=a.concat(eval("Q,[]  (b=Q)[0]?b.charCodeAt():String.fromCharCode(b) 1    [a.join``,a=[]][0] Q+1 a.shift(),[]  i  Q-1".split`Q`.join`a.pop()`.split` `[parseInt(x,36)%19]||0)),a=[])&&a.pop()

카레 구문으로 입력을받는 함수입니다 f(code)(input).


1

파이썬 2 , 258 바이트

s=[]
m=-1
i,p=input()
for c in p.split(' '):
 k=c<"o"
 if c in"yesnowhat":s+=[i if"w"==c[0]else-k+1]
 if c in"surenah":s[m]+=[1,m][k]
 if"p"in c:s.pop(k-1)
 if"oh"==c:s+=[''.join(map(str,s))]
 if"y"==c[m]:s[m]="'"in`s[m]`and ord(s[m])or chr(s[m])
print(s[m])

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


@Wondercricket 덕분에 -3 바이트


1
-1변수 로 저장 하여 4 바이트를 절약 할 수 있습니다
Wondercricket

1

펄 6 ,  233225  바이트

{my @s;{yes=>{@s.push(1)},no=>{@s.push(0)},what=>{@s.push: once slurp},sure=>{++@s.tail},nah=>{--@s.tail},really=>{($/:=@s.tail)~~Int??$/.=chr!!$/.=ord},oh=>{@s.=join},nope=>{@s.shift},yep=>{@s.pop},}{.words}.map:{.()};@s.tail.print}

사용해보세요
Hello World
cat
-1
nul
cat_
0
1

{my @s;{es=>{@s.push(1)},no=>{@s.push(0)},at=>{@s.push: once slurp},re=>{++@s.tail},ah=>{--@s.tail},ly=>->{($_:=@s.tail)~~Int??.=chr!!.=ord},oh=>{@s.=join},pe=>{@s.shift},ep=>{@s.pop},}{.comb(/..»/)}.map:{.()};@s.tail.print}

각 명령에서 마지막 두 문자 만 가져오고 for $_대신 사용한다는 점을 제외하고는 동일하게 작동합니다 .$/really

사용해보십시오 (Hello World)

넓히는:

{
  my @s; # stack

  {  # Associative array
    yes    => {@s.push(1)},
    no     => {@s.push(0)},
    what   => {@s.push: once slurp}, # read everything from $*IN
    sure   => {++@s.tail},
    nah    => {--@s.tail},
    really => {
          ( $/ := @s.tail ) # bind $/ to the last value in the stack
          ~~ Int            # if that is an Int
      ??  $/.=chr           # replace it with that character
      !!  $/.=ord           # otherwise replace it with its ordinal
    },
    oh     => {@s.=join},
    nope   => {@s.shift},
    yep    => {@s.pop},
  }\
  { .words }                # index by the words in the program
  .map: {.()};              # call each of the lambdas in order

  @s.tail.print             # print the last value on the stack
}

1

PHP, 315305 바이트

아직 테스트되지 않은 두 번째 초안

foreach($argv as$k=>$v)if($k>1)eval((strstr($c=preg_replace('#[^a-z ]#','',$v),p)?'':'$s[]=').[yes=>1,no=>0,what=>'$argv[1]',sure=>'array_pop($s)+1',nah:'array_pop($s)-1',really=>'is_int($x=array_pop($s))?chr($x):ord($x)',oh=>'join($s)',nope=>'array_shift($s)',yep=>'array_pop($s)'][$c].';');echo end($s);

로 실행하십시오 php -nr '<php-code>' <input> <yes-code>.

고장

foreach($argv as$k=>$v)if($k>1)         # loop through commands
    eval(                                   # 3. interprete
        (strstr(                            # 2. if no 'p' in command, prepend '$s[]='
                                            # 1. ignore all non-code characters
            $c=preg_replace('#[^a-z ]#','',$v),p)?'':'$s[]=').
        [yes=>1,                                # yes: append 1
        no=>0,                                  # no: append 0
        what=>'$argv[1]',                       # what: append input
        sure=>'array_pop($s)+1',                # sure: remove end, increment, append
        nah:'array_pop($s)-1',                  # nah: remove end, decrement, append
                                                # really: convert between ascii and ordinal
        really=>'is_int($x=array_pop($s))?chr($x):ord($x)',
        oh=>'join($s)',                         # oh: concatenate elements, append
        nope=>'array_shift($s)',                # nope: remove first element
        yep=>'array_pop($s)']                   # yep: remove last element
        [$c]
    .';');
echo end($s);                           # print last element (if exists)
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.