Faça um intérprete para sim!


10

Sim é uma linguagem baseada em pilha que possui algumas instruções separadas por espaço:

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

O último elemento da pilha é sempre emitido no final do programa. Todos os caracteres não alfanuméricos e não espaciais são ignorados. Todo o código é minúsculo. Programas de exemplo:

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

impressões Hello, World!.

what

imprime a entrada ( catprograma).

no nah

impressões -1.

no really

imprime o NULcaractere ( 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

imprime a entrada e um sublinhado.

yes no nope

impressões 0

yes no yep

impressões 1.

Você deve escrever um intérprete no menor número de bytes possível. Aqui está uma implementação de JS (não muito bem-sucedida!):

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>

Veja também minha resposta JS abaixo.

Você pode assumir que todos os números inteiros envolvidos serão menores ou iguais a 126, que reallynunca serão executados com uma sequência de vários caracteres no topo da pilha e que a pilha nunca terá mais de 100 elementos.

Casos de borda

  • yes yes ohimpressões 11.
  • A entrada pode ser uma sequência ou número.
  • O código pode conter quaisquer caracteres. Os que não correspondem [a-z ]devem ser ignorados.

11
Certifique-se de que suas caixas de teste incluam todos os comandos.
Freira vazando

2
Que tipo de números inteiros deve ser usado? Existe excesso? O que reallyfaz se houver uma cadeia de vários caracteres no topo da pilha?
Martin Ender

11
@ programmer5000 Não deve yes yes ohimprimir 11?
User41805 6/17

11
Tudo bem se assumirmos que a entrada contém apenas caracteres pode [a-zA-Z ]?
User41805

11
Pressione a entrada A entrada pode ser um número? Matrizes? Chars? Cordas? Nesse caso, as seqüências de entrada podem ser multilinhas? Incrementar o último item da pilha O que isso faz quando o último item não é um número?
Luis Mendo

Respostas:


4

05AB1E , 77 67 63 61 bytes

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

Assume que o programa está no topo da pilha.

Experimente online!


Você pode realmente assumir que todas as entradas são válidas? Por exemplo, que você não pode obter o programayes no sey yep
Emigna

@ Emigna Não há casos de teste sobre isso, nenhuma especificação, e o OP não esclareceu isso mesmo depois que alguém deixou um comentário.
Okx

Percebi uma falta de casos de teste. Não vi nada nos comentários sobre isso, então me perguntei, pois o programa de referência dele ignora comandos inválidos, enquanto o seu pode executá-los como comandos válidos se a soma dos códigos de caracteres corresponder a um comando válido.
Emigna

9

JavaScript (ES6), 218 215 204 203 bytes

Pega a string do programa se a entrada ina sintaxe de currying (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()

Como?

Usamos a função hash perfeita parseInt(S, 35) % 156 % 9para converter a instrução S em um índice de 0 a 8 e usamos esse índice para selecionar o código JS a ser executado:

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()]

A função P retira o último item da pilha se o carrega em k .

Evitamos que o resultado de algumas instruções seja empurrado de volta para a pilha testando se o método .map () está definido, ou seja, se o resultado for uma matriz. O código para oh está retornando uma matriz por design e forçamos Nope e Yep a retornar matrizes também. Daí a sintaxe:

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

Casos de teste


5

Röda , 256 bytes

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

Experimente online!

Explicação

#variableretorna o comprimento de variable(se for uma string ou uma matriz).

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

Pitão , 69 bytes

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

Experimente online!


Parece não funcionar no programa "Olá, Mundo".
Okx

@Okx Funciona; Eu mudei o programa no meu link; o programa original é muito longo.
Leaky Nun

Ou vários outros programas, nesse caso. 013456789yes 012345678no ohimprime 0, a saída esperada é 10.
Okx 8/17

Também não funciona para o caso de borda yes yes oh(especificado na pergunta), a saída esperada é 11.
Okx

@Okx Veja os comentários. O OP especificou isso especificamente como comportamento indefinido.
Leaky Nun

1

JS (ES6), 361 340 bytes

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

Leva código e entrada através de currying.

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

JavaScript (ES6), 220 216 bytes

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

Uma função que recebe entrada com sintaxe de curry, como f(code)(input).


1

Python 2 , 258 bytes

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])

Experimente online!


-3 bytes graças a @Wondercricket


11
Você pode salvar 4 bytes, armazenando -1como uma variável
Wondercricket

1

Perl 6 ,  233  225 bytes

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

Experimente
Olá mundo
gato
-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}

Funciona da mesma forma, exceto que apenas captura os dois últimos caracteres de cada comando e usa em $_vez de $/para really.

Experimente (Olá Mundo)

Expandido:

{
  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 bytes

segundo rascunho, ainda não testado

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

Corra com php -nr '<php-code>' <input> <yes-code>.

demolir

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)
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.