Your task, if you wish to accept it, is to write a program that outputs a non-zero number(can be integer or float). The tricky part is that if I reverse your source code, the output must be the original integer negated.
Rules
You must build a full program. That is, your output has to be printed to STDOUT.
Both the numbers must be in base 10 (outputting them in any other base or with scientific notation is forbidden).
Outputting the numbers with trailing / leading spaces is allowed.
This is code-golf, so the shortest (original) code in each language wins!
Default Loopholes apply.
Example
Let's say your source code is ABC
and its corresponding output is 4
. If I write CBA
instead and run it, the output must be -4
.
72 Answers 72
05AB1E, 2 bytes
(1
( # negate nothing
1 # push 1 (and implictly output it)
1 # push 1
( # negate it (and implictly output it)
-
21\$\begingroup\$ +1 for "!enilno ti yrT".. \$\endgroup\$Nat– Nat2019年09月19日 09:58:14 +00:00Commented Sep 19, 2019 at 9:58
PowerShell, (削除) 4 (削除ここまで) 3 bytes
1-0
Try it online! or !enilno ti yrT
Golfed a byte by using arithmetic instead of the number-comment-number format.
This is apparently also the same as jshell (per Sam), and jq (per manatwork -- 1-0
and 0-1
).
-
\$\begingroup\$ The same in jshell \$\endgroup\$Sam– Sam2019年09月19日 10:59:14 +00:00Commented Sep 19, 2019 at 10:59
-
1
JavaScript (V8), 19 bytes
print(1)//)1-(tnirp
almost identical to...
C# (Visual C# Interactive Compiler), 19 bytes
Print(1)//)1-(tnirP
(thanks to @someone for pointing it out)
still pretty much the same in...
Lua, 19 bytes
print(1)--)1-(tnirp
but shorter in...
Python 2, 15 bytes
print 1#1-tnirp
Even shorter in PHP, because it has this magic printing tool: <?=
...
PHP, 12 bytes
<?=1;#;1-=?<
Even shorterer in Ruby, because you can inspect
rather than print
Ruby, 8 bytes
p 1#1- p
-
\$\begingroup\$ Also C# Interactive,
Print(1)//)-1(tnirP
. (Try it online!) \$\endgroup\$the default.– the default.2019年09月17日 14:04:19 +00:00Commented Sep 17, 2019 at 14:04 -
\$\begingroup\$ For C#, the shortest program is likely also the trivial one:
class A{static void Main(){System.Console.Write(1);}}//}};)1-(etirW.elosnoC.metsyS{)(niaM diov citats{A ssalc
\$\endgroup\$LegionMammal978– LegionMammal9782019年09月18日 00:38:58 +00:00Commented Sep 18, 2019 at 0:38 -
1\$\begingroup\$ Not a programming language, but you can do
1<!--!<1-
(9 bytes) with HTML, which will be-1<!--!<1
when reversed. It does exactly the same as your answer. \$\endgroup\$Ismael Miguel– Ismael Miguel2019年09月18日 10:08:02 +00:00Commented Sep 18, 2019 at 10:08 -
\$\begingroup\$ Mostly the same in Lua:
print(1)--)1-(tnirp
\$\endgroup\$val - disappointed in SE– val - disappointed in SE2019年09月18日 19:10:45 +00:00Commented Sep 18, 2019 at 19:10 -
1\$\begingroup\$ @EricDuminil: codegolf.stackexchange.com/a/193169/81663 \$\endgroup\$Night2– Night22019年09月19日 11:33:10 +00:00Commented Sep 19, 2019 at 11:33
///, 4 bytes
9/9-
Outputs 9
.
Reversed:
-9/9
Outputs -9
.
Everything before the /
is printed, while the rest is ignored (not really used slashes much so I don't know exactly what happens, but it doesn't output anything).
-
2\$\begingroup\$ +1 for using Slashes. The
/
begins the pattern-reading process, and thus, the characters after it is readed into the pattern, not outputted. \$\endgroup\$TwilightSparkle– TwilightSparkle2019年09月17日 14:09:17 +00:00Commented Sep 17, 2019 at 14:09 -
2\$\begingroup\$ I came up with
/\-//1-
and thought I was clever. :D \$\endgroup\$Sophie Swett– Sophie Swett2019年09月19日 00:44:38 +00:00Commented Sep 19, 2019 at 0:44
Whitespace, 21 bytes
S S S T N
T N
S T N
N
N
T S N
T N
T T S S
Letters S
(space), T
(tab), and N
(new-line) added as highlighting only.
Outputs 1
/-1
.
Try it online or try it online reversed (with raw spaces, tabs and new-lines only).
Explanation:
Utilizing the Exit Program builtin being a short palindrome NNN
.
The regular program will:
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
The reverse program will:
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
Small additional explanation of pushing a number:
- First
S
: Enable Stack Manipulation - Second
S
: Push a number to the stack S
orT
: Positive/negative respectively- Some
S
/T
followed by a trailingN
: number in binary, whereS=0
andT=1
I.e. SSTTSTSN
pushes -10
.
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.)
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 -[
or nothing depending on the sign of the top of the stack. So...
Stack Cats -n
, 11 bytes
*|]I*:*I[|*
Try it online! The footer again includes all other alternatives at the same byte count. Some of those output 1/-1 and some output 2/-2 as indicated after each program. I picked this one to explain kinda randomly as one of the ones that output 2.
Explanation
As I said, this one's a bit longer. Even if we did use the -m
notation for this, it would weigh in at 6 bytes instead of the above 4.
The commands in use this time:
* 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.
The first program only uses two stacks. That's a bit messy to do in ASCII art, but I'll try my best. The square brackets indicate which stack the tape head is on, and I'll put the commands between each pair of stack states.
[-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
... ...
Now the -1
acts as an EOF marker and the 2
gets printed.
The other program is the same until the [
. It's still virtually the same all the way until the second I
. We'll technically be on a different stack, but without values on them, they're all indistinguishable. But then the difference between I[
and I]
ends up mattering:
*|[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
... ... ...
And this time, we don't have an EOF marker, but the program still outputs the -2
.
Klein 011, 5 bytes
1-
@/
Reversed
/@
-1
These take advantage of Klein's unique topology, specifically the real projective plane. (Although individually each answer only needs a Klein bottle).
Haskell without comments, 41 bytes
Forwards prints 1
+ newline:
main=print$!1
niam=main
"1-"!$rtStup=niam
Reversed prints -1
with no newline (which could be added at a cost of 2 bytes):
main=putStr$!"-1"
niam=main
1!$tnirp=niam
- 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).
- For
- 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.
-
3\$\begingroup\$ This also works in TI-Basic \$\endgroup\$pizzapants184– pizzapants1842019年09月19日 20:30:09 +00:00Commented Sep 19, 2019 at 20:30
-
2\$\begingroup\$ "output" here isn't well defined for the entire search engine Google. Did you mean, specifically, Google's Calculator? \$\endgroup\$thejonymyster– thejonymyster2022年06月27日 22:34:31 +00:00Commented Jun 27, 2022 at 22:34
-
1\$\begingroup\$ Also works in python IDLE \$\endgroup\$The Empty String Photographer– The Empty String Photographer2023年05月27日 08:24:35 +00:00Commented May 27, 2023 at 8:24
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;
-
\$\begingroup\$ That's clever. Nice! \$\endgroup\$AdmBorkBork– AdmBorkBork2019年09月19日 13:14:41 +00:00Commented Sep 19, 2019 at 13:14
-
1\$\begingroup\$ Man, it's sad that I've arrived to the same answer as you, 3 hours late :( Have my upvote. \$\endgroup\$Ismael Miguel– Ismael Miguel2019年09月19日 14:58:41 +00:00Commented Sep 19, 2019 at 14:58
-
\$\begingroup\$ Nice! 12 bytes using
<?=1;#;1-=?<
too! \$\endgroup\$Dom Hastings– Dom Hastings2024年04月30日 13:45:25 +00:00Commented Apr 30, 2024 at 13:45
Japt, 2 bytes
Any single digit integer >0
can be used in place of the 2
as can A-G
, H
, I
, J
or L
(10-16
, 32
, 64
, -1
& 100
, respectively).
n2
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.
Cubix, (削除) 7 (削除ここまで) (削除) 6 (削除ここまで) 5 bytes
@)O(@
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@
Not as short, but aesthetically pleasing.
-
\$\begingroup\$ nice, way to put it on a size 1 cube! \$\endgroup\$Giuseppe– Giuseppe2019年09月17日 19:53:50 +00:00Commented Sep 17, 2019 at 19:53
-
4\$\begingroup\$
@)O(@
for 5 bytes and restoration of symmetry :) \$\endgroup\$MickyT– MickyT2019年09月17日 22:01:53 +00:00Commented Sep 17, 2019 at 22:01
T-SQL, 16 bytes
--Forwards:
PRINT 4--4-TNIRP
--Backwards:
PRINT-4--4 TNIRP
Picked 4 because 1 is overused :)
-
1\$\begingroup\$ If you are curious, an answer for MySQL would be
select 1#1-tceles
(17 bytes). You can check the result on sqlfiddle.com/#!9/9eecb/107825. \$\endgroup\$Ismael Miguel– Ismael Miguel2019年09月18日 10:17:20 +00:00Commented Sep 18, 2019 at 10:17
Jelly, 2 bytes
NC
N
egative, results in 0
, then C
omplement, results in 1-0
= 1
.
CN
Try it online!
C
omplement, results in 1-0
= 1
. N
egative, results in -1
.
Hexagony, 5 bytes
1!@!(
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.
-
\$\begingroup\$ +1 for proof of optimality in an otherwise trivial answer \$\endgroup\$Jo King– Jo King2019年09月23日 00:48:23 +00:00Commented Sep 23, 2019 at 0:48
Runic Enchantments, 4 bytes
1@Z1
Try it online! Try it Reversed!
I couldn't find a way to re-use the 1
command, even at the expense of a byte or two.
1@ɩ
also works, but is the same number of bytes.
-
\$\begingroup\$ Why the input? The question said your program must take no input. \$\endgroup\$TwilightSparkle– TwilightSparkle2019年09月17日 13:51:46 +00:00Commented Sep 17, 2019 at 13:51
-
\$\begingroup\$ @TwilightSparkle I misread and already fixed it \$\endgroup\$Draco18s no longer trusts SE– Draco18s no longer trusts SE2019年09月17日 13:52:52 +00:00Commented Sep 17, 2019 at 13:52
-
\$\begingroup\$ Yeah, I see. Clever. \$\endgroup\$TwilightSparkle– TwilightSparkle2019年09月17日 13:54:06 +00:00Commented Sep 17, 2019 at 13:54
Zsh, 12 bytes
<<<2 # 2-<<<
Basic forward, comment, reverse method.
If I/O is less restrictive, then a more interesting 11 byte solution is possible thanks to Zsh supporting negative return codes:
return -127
Reversed, 721- nruter
exits with code 127
(command not found). exit -127
cannot be used, it would be cast to a u8
.
Try it online!
APL (Dyalog Unicode), (削除) 4 (削除ここまで) 3 bytes
1-0
Trivial answer. Prints 1
when run and ̄1
when run reversed.
CJam, 3 bytes
W;1
Try it online!
How they work
Normal version:
W e# Push -1
; e# Delete
1 e# Push 1
e# Implicit display
Reverse version: you get the idea.
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
Retina, 6 bytes
-`<
-
Prints 1
.
-
<`-
Prints -1
.
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.
Wolfram Language (Mathematica), (削除) 21 (削除ここまで) 18 bytes
Print@1;tnirP//1-0
-3 thanks to Martin Ender
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 \$\iff\$shift(E) = 0
, similarly it's useful in the backward program \$\iff\$shift(D) = 0
. However ifshift(D) = shift(E) = 0
then the programB
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 becauseord('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
.
Google Sheets, 12
Fun problem!
Forward:
=1+N("(N+1-=
Backward:
=-1+N("(N+1=
Google sheets auto-closes quotes and parens. N(string)
is always 0.
-
1\$\begingroup\$ docs.google.com/spreadsheets/d/… Cool answer! \$\endgroup\$Razetime– Razetime2020年08月06日 02:30:01 +00:00Commented Aug 6, 2020 at 2:30
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.
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
-
2\$\begingroup\$ I don't know Go, but it seems you can remove a few bytes. The
Println
can bePrint
, and theimport "fmt";
doesn't need the space:import"fmt";
. :) \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2019年09月19日 08:52:41 +00:00Commented Sep 19, 2019 at 8:52
Perl 5 (-p), 12 bytes
\$--{}}{++$\
The }{
pseudo-operator really comes in handy.
Perl 5 (-M5.010), 9 bytes
Provided by Nahuel Fouilleul in a comment
say+1-yas
-
2\$\begingroup\$ should be
say 1#1-yas
\$\endgroup\$Nahuel Fouilleul– Nahuel Fouilleul2019年09月17日 15:24:43 +00:00Commented Sep 17, 2019 at 15:24 -
\$\begingroup\$ @NahuelFouilleul yas indeed \$\endgroup\$Grimmy– Grimmy2019年09月17日 15:27:51 +00:00Commented Sep 17, 2019 at 15:27
-
2\$\begingroup\$ 9 bytes :
say+1-yas
andsay-1+yas
\$\endgroup\$Nahuel Fouilleul– Nahuel Fouilleul2019年09月18日 04:56:41 +00:00Commented Sep 18, 2019 at 4:56
-
(0x45 = 0b00101101) works in Jelly --
yields -1 since it defines the literal -1, whileṆ
(0xB4 = 0b10110100) yields 1 since it performs a logical not of the implicit input of zero. (Of courseṆ
works just as well :p) \$\endgroup\$