Invierto el código fuente, ¡tú niegas la salida!


39

Su tarea, si desea aceptarlo, es escribir un programa que genere un número distinto de cero (puede ser entero o flotante). La parte difícil es que si invierto su código fuente, la salida debe ser el entero original negado.

Reglas

  • Debes construir un programa completo . Es decir, su salida debe imprimirse en STDOUT.

  • Ambos números deben estar en la base 10 (está prohibido enviarlos a cualquier otra base o con notación científica).

  • La salida de los números con espacios finales / iniciales está permitida.

  • Este es el código de golf, por lo que gana el código más corto (original) en cada idioma.

  • Se aplican las lagunas predeterminadas.

Ejemplo

Digamos que su código fuente es ABCy su salida correspondiente es 4. Si escribo en su CBAlugar y lo ejecuto, la salida debe ser -4.


66
Si pudiéramos revertir en el nivel de bits en lugar del nivel de bytes, el un byte -(0x45 = 0b00101101) funciona en Jelly - -produce -1 ya que define el literal -1, mientras que (0xB4 = 0b10110100) produce 1 ya que realiza una lógica no de la entrada implícita de cero. (Por supuesto, funciona igual de bien: p)
Jonathan Allan

@TwilightSparkle ¿"tener una entrada vacía no utilizada" significa que podemos confiar en que las funciones de entrada lleguen inmediatamente a EOF?
Borka223

1
@ Borka223 No, no puedes.
HighRadioactive

Copia @JoKing. Quitaré eso.
HighRadioactive

Respuestas:



28

JavaScript (V8) , 19 bytes

print(1)//)1-(tnirp

Pruébalo en línea!


casi idéntico a ...

C # (compilador interactivo de Visual C #) , 19 bytes

Print(1)//)1-(tnirP

Pruébalo en línea!

(Gracias a @ alguien por señalarlo)


sigue siendo casi lo mismo en ...

Lua , 19 bytes

print(1)--)1-(tnirp

Pruébalo en línea!


pero más corto en ...

Python 2 , 15 bytes

print 1#1-tnirp

Pruébalo en línea!


Incluso más corto en PHP, porque tiene esta herramienta mágica de impresión: <?=...

PHP , 12 bytes

<?=1;#;1-=?<

Pruébalo en línea!


Incluso acortador en Ruby, porque puedes en inspectlugar de imprimir

Rubí , 8 bytes.

p 1#1- p

Pruébalo en línea!


También C # interactivo, Print(1)//)-1(tnirP. (¡ Pruébelo en línea! )
mi pronombre es monicareinstate el

Para C #, el programa más corto es probablemente también el trivial: class A{static void Main(){System.Console.Write(1);}}//}};)1-(etirW.elosnoC.metsyS{)(niaM diov citats{A ssalc
LegionMammal978

No es un lenguaje de programación, pero puede hacerlo 1<!--!<1-(9 bytes) con HTML, que será -1<!--!<1cuando se invierte. Hace exactamente lo mismo que su respuesta.
Ismael Miguel

Más o menos lo mismo en Lua:print(1)--)1-(tnirp
Val dice Reinstate Monica el



12

/// , 4 bytes

9/9-

Salidas 9.

Pruébalo en línea!

Invertido:

-9/9

Salidas -9.

Pruébalo en línea!

Todo antes de que /se imprima, mientras que el resto se ignora (no se usan mucho las barras, así que no sé exactamente qué sucede, pero no genera nada).


2
+1 por usar barras inclinadas. El /comienza el proceso de patrón de lectura, y por lo tanto, los caracteres después de que se readed en el patrón, no emitida.
HighRadioactive

2
Se me ocurrió /\-//1-y pensé que era inteligente. : D
Tanner Swett


10

Espacio en blanco , 21 bytes

S S S T N
T   N
S T N
N
N
T   S N
T   N
T   T   S S 

Letras S(espacio), T(tabulación) yN agregaron (nueva línea) solo como resaltado.

Salidas 1/ -1.

Pruébelo en línea o en línea al revés (solo con espacios en bruto, pestañas y nuevas líneas).

Explicación:

Utilizando el programa de salida incorporado es un palíndromo corto NNN.
El programa regular:

SSSTN  # Push 1 to the stack
TNST   # Pop and print the top of the stack as number
NNN    # Exit the program, making everything after it no-ops

El programa inverso:

SSTTN  # Push -1 to the stack
TNST   # Pop and print the top of the stack as number
NNN    # Exit the program, making everything after it no-ops

Pequeña explicación adicional de presionar un número:

  • primero S : Habilite la manipulación de la pila
  • Segundo S: empujar un número a la pila
  • S o T : Positivo / negativo respectivamente
  • Algunos S/ Tseguido de un final N: número en binario, donde S=0yT=1

Es decir, SSTTSTSNempuja -10.


7

T-SQL, 16 bytes

--Forwards:
PRINT 4--4-TNIRP

--Backwards:
PRINT-4--4 TNIRP

Escogió 4 porque 1 está sobreutilizado :)


1
Si tiene curiosidad, una respuesta para MySQL sería select 1#1-tceles(17 bytes). Puede verificar el resultado en sqlfiddle.com/#!9/9eecb/107825 .
Ismael Miguel

7

Japt , 2 bytes

Cualquier número entero de un solo dígito >0se puede utilizar en lugar de la 2Can A-G, H, I, Jo L( 10-16, 32, 64, -1y 100, respectivamente).

n2

Probarlo | Invertido

The n method when applied to an integer, subtracts that integer from the argument passed to it, which defaults to 0. When run forwards, the n method is being run on the implicit first input, which also defaults to 0.

Alternatively, the g method could be used instead of n, which gives the sign of the result of subtracting its argument from the integer it's applied to.


7

Haskell without comments, 41 bytes

Forwards prints 1 + newline:

main=print$!1
niam=main
"1-"!$rtStup=niam

Try it online!

Reversed prints -1 with no newline (which could be added at a cost of 2 bytes):

main=putStr$!"-1"
niam=main
1!$tnirp=niam

Try it online!

  • The first line of each program prints the number.
    • For -1 string output is used to avoid parentheses.
    • Using $! (strict application) instead of a space allows the reversed line to be a valid definition of the operator !$ (just $ wouldn't do since the redefinition would break the use).
  • The middle line ensures that niam is defined for the last line.
  • The last line is a definition of an operator !$, which is not used but needs to parse and typecheck correctly.

7

PHP, 15 13 bytes

A PHP version without comment abuse. ohce is an undefined constant, so it will be equal to string value of its name. As a result, this will try to print +1-'ohce' or -1+'ohce' when reversed. Since 'ohce' is a non-numeric value, 0 will be used instead in the arithmetic operations and only 1 or -1 will be printed.

;echo+1-ohce;

Try it online!

‮Try it online!


That's clever. Nice!
AdmBorkBork

1
Man, it's sad that I've arrived to the same answer as you, 3 hours late :( Have my upvote.
Ismael Miguel




6

Cubix, 7 6 5 bytes

@)O(@

Try it here
Reversed

Explanation

Cubified:

  @
) O ( @
  .

Unrolling the control flow, we execute )O(@, which increments, outputs, decrements, and exits.

Reversed and cubified:

  @
( O ) @
  .

Unrolling the control flow, we execute (O)@, which decrements, outputs, increments, and exits.

Previous version

@O(.)O@

Try it here
Reversed

Not as short, but aesthetically pleasing.


nice, way to put it on a size 1 cube!
Giuseppe

3
@)O(@ for 5 bytes and restoration of symmetry :)
MickyT



5

Stack Cats -mn, 4 bytes

:-:_

Try it online! In the footer I've included all other 4-byte solutions. (Stack Cats ignores everything after the first linefeed.)

Try the reverse!

Explanation

The -n flag turns on numeric output (and input, but we don't have any), and the -m flag is normally just a golfing convenience which lets you avoid the redundant part of the source code. This is because every Stack Cats program needs to have mirror symmetry. With the -m flag you only give it the first half (plus the central character). So the actual program here is:

:-:_:-:

As you can see in the first TIO link, there's a ton of 4-byte solutions, but I picked this one for its simplicity. Stack Cats is stack-based, and this program only uses the initial stack. Since we don't have any input, it contains a single -1 (an EOF marker) on top of an infinite well of zeros. The three commands in the program have the following meaning:

:   Swap the top two stack elements.
-   Negate the top stack element (i.e. multiply by -1).
_   Pop a. Peek b. Push b-a.

So here is how the program modifies the stack (states and commands are staggered to indicate how each command changes the stack from one state to the next):

   :   -   :   _   :   -   :

-1   0   0  -1   1   0   0   1
 0  -1  -1   0   0   1   1   0
 0   0   0   0   0   0   0   0
 …   …   …   …   …   …   …   …

As it turns out, the only command that really does anything here is _ which turns our EOF marker into a 1. Output at the end of the program is implicit, and the EOF marker is optional, so this just prints out the 1 we get.

Now if we reverse the source code, due to the implicit mirroring, the actual program becomes:

_:-:-:_

This does something very different:

   _   :   -   :   -   :   _

-1   1   0   0   1  -1   0  -1
 0   0   1   1   0   0  -1  -1
 0   0   0   0   0   0   0   0
 …   …   …   …   …   …   …   …

This time the bottom of the stack is still a -1 so it does act as the EOF marker and only the -1 on top of it gets printed.

...

Now with all of that said, since Stack Cats has such a unique relationship with reversing code, I feel that using -m is a little cheating. It's normally only meant to save bytes by omitting the redundant part of the source code, but here it actually makes the challenge a lot easier and even the full program shorter. This is because reversing a full program will only change the program if it contains any of <>[], which also means that the program ends up making use of multiple stacks (Stack Cats actually has a tape of stacks, where all but the initial one are only filled with zeros to begin with). Furthermore, reversing it then just swaps the <> and [] pairs, which still makes the execution symmetric. The only way to break that symmetry is to use I which does -] or -[o nada dependiendo del signo de la parte superior de la pila. Asi que...


Pila de gatos -n , 11 bytes

*|]I*:*I[|*

Pruébalo en línea! El pie de página nuevamente incluye todas las otras alternativas en el mismo conteo de bytes. Algunas de esas salidas 1 / -1 y algunas salidas 2 / -2 como se indica después de cada programa. Elegí este para explicar un poco al azar como uno de los que producen 2.

¡Intenta lo contrario!

Explicación

Como dije, este es un poco más largo. Incluso si usáramos el-m notation for this, it would weigh in at 6 bytes instead of the above 4.

Los comandos en uso esta vez:

*   Toggle the least significant bit of the top of the stack.
|   Reverse the longest non-zero of prefix on this stack.
[]  Move one stack to the left/right and take the top of the current stack with you.
I   If the top of the stack is positive, -], if it's negative, -[, otherwise do nothing.
:   Swap the top two stack elements.

El primer programa solo usa dos pilas. Eso es un poco complicado de hacer en el arte ASCII, pero haré lo mejor que pueda. Los corchetes indican en qué pila está el cabezal de la cinta, y pondré los comandos entre cada par de estados de pila.

  [-1]
…   0   0   …
    0   0
    …   …

      *

  [-2]
…   0   0   …
    0   0
    …   …

      | (does nothing)
      ]

      [-2]
…   0   0   …
    0   0
    …   …

      I

   [2]
…   0   0   …
    0   0
    …   …

      *

   [3]
…   0   0   …
    0   0
    …   …

      :

   [0]
…   3   0   …
    0   0
    …   …

      *

   [1]
…   3   0   …
    0   0
    …   …

      I

      [-1]
…   3   0   …
    0   0
    …   …

      [

  [-1]
…   3   0   …
    0   0
    …   …

      |

  [ 3]
…  -1   0   …
    0   0
    …   …

      *

  [ 2]
…  -1   0   …
    0   0
    …   …

Ahora el -1actúa como un marcador EOF y el2 se imprime.

El otro programa es el mismo hasta que [. Sigue siendo prácticamente igual hasta el segundo I. Técnicamente estaremos en una pila diferente, pero sin valores en ellos, todos son indistinguibles. Pero entonces la diferencia entre I[y I]termina importando:

    *|[I*:*I

      [-1]
…   3   0   0   …
    0   0   0
    …   …   …

        ]

          [-1]
…   3   0   0   …
    0   0   0
    …   …   …

        | (does nothing)
        *

          [-2]
…   3   0   0   …
    0   0   0
    …   …   …

Y esta vez, no tenemos un marcador EOF, pero el programa aún genera el -2.


4

Zsh , 12 bytes

<<<2 # 2-<<<

Pruébalo en línea!

Método básico de reenvío, comentario y reversa.


Si la E / S es menos restrictiva, entonces es posible una solución más interesante de 11 bytes gracias a que Zsh admite códigos de retorno negativos:

return -127

Invertido, 721- nrutersale con código 127(comando no encontrado). exit -127no se puede usar, se lanzaría a a u8. Pruébalo en línea!


4

CJam , 3 bytes

W;1

Pruébalo en línea!

Cómo trabajan ellos

Versión normal:

W    e# Push -1
;    e# Delete
1    e# Push 1
     e# Implicit display

Versión inversa: captas la idea.


4

MATL, 3 bytes

Nqv

Try it online!

How they work

Normal:

N   % Push number of elements in the stack: 0
q   % Subtract 1: gives -1
v   % Concatenate stack contents vertically: leaves -1 as is
    % Implicit display stack contents

Reversed:

v   % Concatenate stack contents vertically: gives the empty array, []
q   % Subtract 1: leaves [] as is
N   % Push number of elements in the stack: 1
    % Implicit display. [] is not displayed


4

Hexagony, 5 bytes

1!@!(

Try it online!

Any valid program must:

  • Have a termination command (@ or :). The latter is only different for the former when there's a memory pointer movement command. Also this command must not be at the first or the last byte.
  • Have an output command. (!, ; is also possible but would probably take more bytes)
  • Have a memory manipulation command.

Therefore a 2-byte program is obviously impossible. A 3-byte program is impossible because the second byte must be the termination command, and the first byte must not be a mirror/IP manipulation command, therefore only 1 byte can be executed.

I think a 4-byte program is not possible. Such a program must have the form a@bc with hexagonal grid

 Forward:       | Backward:
                | 
  c b           |   a @
 @ a .          |  b c .
  . .           |   . .

Therefore a must be a IP redirection command. However it's impossible to generate both positive and negative number with only 1 memory manipulation command.


+1 for proof of optimality in an otherwise trivial answer
Jo King



3

Java 5 or 6, 127 67 bytes

enum A{A;{System.out.print(9);}}//}};)9-(tnirp.tuo.metsyS{;A{A mune

Outputs 9/-9.

No online compiler, because Java 5 or 6 isn't available anywhere.

You can however try this 127 bytes Java 8 equivalent:
Try it online or try it online reversed.

Explanation:

enum A{                              // Create an enum
 A;                                  //  With a mandatory value
 {                                   //  And in a separate instance code-block:
  System.out.print(9);}}             //   Print 9 to STDOUT
//}};)9-(tnirp.tuo.metsyS{;A{A mune  // Comment and thus a no-op

Java 5 and 6 had a bug allowing you to create a code block inside an enum to do something, despite missing a program's mandatory main-method. This will result in an error:

java.lang.NoSuchMethodError: main
Exception in thread "main"

But will still output what we'd want to STDOUT first, so we can ignore that.


3

Golang, 109 bytes

package main;import "fmt";func main(){fmt.Println(1)}//})1(nltnirP.tmf{)(niam cnuf;"tmf" tropmi;niam egakcap

And its reverse:

package main;import "fmt";func main(){fmt.Println(-1)}//})1(nltnirP.tmf{)(niam cnuf;"tmf" tropmi;niam egakcap

Try it online!


2
I don't know Go, but it seems you can remove a few bytes. The Println can be Print, and the import "fmt"; doesn't need the space: import"fmt";. :)
Kevin Cruijssen


3

Retina, 6 bytes

-`<
-

Prints 1.

Try it online!



-
<`-

Prints -1.

Try it online!

Explanation: 1

-`<
-

This... does nothing. Due to the `, this is a substitution from < to - (with configuration -, which does nothing), but the input is empty, so the output is empty as well.


And this second stage matches the empty regex against the empty input and counts the number of matches, which is exactly 1. Output is implicit.

Explanation: -1


-

This time we replace the empty regex with -. This does indeed turn the empty input into a single -.

<`-

Here, the configuration actually does something: < prints the stage's input before executing the stage, so we print the -. Then - counts the hyphens in the stage's input which is again 1. Due to the implicit output, this prints a 1 after the -, giving us -1 as required.


3

TEX(MathJax), 4bytes

1%1-

CodeResultForward:1%1-1Backward:-1%11


3

brainfuck, 156 bytes

+++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++<+++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++

Try it online! / Forward/backward verifier in Bash

Prints -1 forward and \n1 backwards.

Despite being almost trivial, I believe this is the optimal solution for this particular fixed output.

Proof:

  • The program cannot have [ or ].

    Therefore the program must have the form <A> . <B> . <C>.

  • Each , can be replaced with a sufficient number of < without increasing the number of + or -.

  • Each + is only useful in either the forward or the backward program, never both.

    Proof: + in part A is obviously only useful in the forward program, and + in part C is obviously only useful in the backward program.

    Denote shift(P) = number of < in P - number of > in P. Consider program <B> = <D> + <E>, the + in the middle is useful in the forward program shift(E) = 0, similarly it's useful in the backward program shift(D) = 0. However if shift(D) = shift(E) = 0 then the program B executed either forward or backward would add a fixed value to the current cell before printing the second time, which can't be the case because ord('1') - ord('\n') != ord('1') - ord('-').

Therefore the program needs at least ord('-')+ord('1')+ord('\n')+ord('1') = 153 +s, 2 .s, and at least a < > or , because shift(B) != 0.

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.