| Bytes | Lang | Time | Link |
|---|---|---|---|
| 119 | Malbolge Unshackled | 250730T122636Z | Weird Gl |
| 007 | Raku Perl 6 rakudo | 250421T172411Z | xrs |
| 110 | Bespoke | 250320T091858Z | Josiah W |
| 004 | TIBasic TI83 | 250318T095137Z | MarcMush |
| 012 | Desmos | 250318T022214Z | DesmosEn |
| 044 | SAKO | 250317T202659Z | Acrimori |
| 022 | YASEPL | 250121T191747Z | madeforl |
| 172 | jBasher2 | 250121T190221Z | madeforl |
| nan | 241010T090812Z | RARE Kpo | |
| 023 | Swift | 240316T162022Z | macOSist |
| 068 | COBOL GNU | 230802T152427Z | DDS |
| 039 | floor | 230801T102346Z | bsoelch |
| 008 | Desmoslang | 230530T035831Z | Dadsdy |
| 001 | Thunno 2 | 230528T142721Z | The Thon |
| 004 | Regex Generic | 230324T082014Z | Deadcode |
| 026 | Lua | 210302T055059Z | Deadcode |
| 012 | Alice | 210604T110531Z | SjoerdPe |
| 017 | Binaryencoded Golfical | 230323T000111Z | SuperJed |
| 014 | Arturo | 230323T004940Z | chunes |
| nan | Piet + asciipiet | 220425T020310Z | Bubbler |
| 021 | Trilangle | 230315T123030Z | Bbrk24 |
| 002 | Thunno | 230315T094855Z | The Thon |
| 018 | A0A0 | 220524T154055Z | stefvans |
| 021 | Microscript II | 220524T125438Z | Ginger |
| 015 | GNU AWK | 210604T141731Z | Pedro Ma |
| 001 | Risky | 210818T185937Z | Adam |
| 004 | Julia | 220208T100314Z | MarcMush |
| 032 | tinylisp | 220205T035732Z | Razetime |
| 021 | tinylisp | 220207T174138Z | DLosc |
| 004 | K ngn/k | 220205T144005Z | coltim |
| 024 | Python 3 | 211101T092327Z | Stephen |
| 019 | Zsh | 210306T002341Z | roblogic |
| 047 | Python 3.8 | 210914T175553Z | Larry Ba |
| 008 | BitCycle U | 210818T045237Z | DLosc |
| 001 | Japt | 170110T192748Z | Oliver |
| 025 | Pxem | 210316T140700Z | user1004 |
| 001 | Vyxal | 210421T081426Z | wasif |
| 009 | x86 | 210421T060241Z | l4m2 |
| 001 | Vyxal | 210421T044559Z | Aaroneou |
| 021 | R | 210401T144115Z | Robin Ry |
| 024 | x86_64 machine code | 210329T084327Z | Febriyan |
| 008 | BRASCA | 210329T091413Z | SjoerdPe |
| 023 | Python | 210315T204218Z | user1008 |
| 012 | Java | 210305T224430Z | Unmitiga |
| 002 | Stax | 210305T175446Z | user8965 |
| 1246 | Mornington Crescent | 200422T230151Z | Cloudy7 |
| 075 | COW | 200413T010219Z | Domenico |
| 003 | 8th | 170110T091305Z | Chaos Ma |
| 091 | asm2bf | 200411T170040Z | Kamila S |
| 006 | Haskell | 200411T163806Z | umnikos |
| 002 | J | 200411T162126Z | PkmnQ |
| 498 | ArnoldC | 200402T110844Z | Mukundan |
| 012 | Desmos | 200326T075912Z | sportzpi |
| 007 | dc | 200326T074626Z | Mitchell |
| 025 | Python 3 | 200326T073755Z | Dion |
| 026 | Symja | 200326T020045Z | lyxal |
| 028 | Io | 200326T014320Z | user9206 |
| 944 | Scratch 3.0 | 200127T052250Z | lyxal |
| 021 | PowerShell | 161220T142836Z | AdmBorkB |
| 025 | Python 3 | 200305T070944Z | Surculos |
| 008 | Gol><> | 180330T080547Z | Bubbler |
| 030 | Python 3 | 200302T051446Z | user9206 |
| 002 | 05AB1E | 200126T233339Z | user8505 |
| 013 | Keg | 200126T090037Z | lyxal |
| 064 | naz | 200121T053400Z | sporebal |
| 140 | F# | 180506T005402Z | Ciaran_M |
| 002 | Canvas | 180327T233337Z | hakr14 |
| 057 | TIS n 1 1 | 180329T212842Z | Phlarx |
| 1815 | Hexagony | 180320T145358Z | Adyrem |
| 038 | BrainFlak | 180115T002316Z | Jo King |
| 026 | MachineCode | 180327T183945Z | MD XF |
| 040 | BrainFlueue | 180327T181104Z | MegaTom |
| 016 | Hexagony | 180327T124446Z | Jo King |
| 068 | Whitespace | 180320T132644Z | Kevin Cr |
| 131 | Minecraft Functions 18w11a | 180320T034859Z | Noskcaj |
| 044 | Swift | 180320T000628Z | user3151 |
| 020 | SHELL 20 Bytes | 180319T235719Z | Ali ISSA |
| 002 | Stax | 180319T232259Z | Weijun Z |
| 087 | FORTRAN 77 | 180319T230929Z | rafa1111 |
| 012 | Befunge93 PyFunge | 180216T224716Z | MercyBea |
| 051 | Lua 51 Bytes | 180216T232352Z | Alex All |
| 013 | Befunge 93 | 170104T013418Z | MercyBea |
| 001 | Pyt | 180216T221148Z | mudkip20 |
| 9110 | Perl 5 | 180216T215601Z | Xcali |
| 016 | Yabasic | 180216T142329Z | Taylor R |
| 028 | Functoid | 180114T212655Z | ბიმო |
| 011 | Deorst | 180114T184213Z | caird co |
| 009 | Add++ | 171031T190136Z | caird co |
| 016 | REXX | 171121T091330Z | idrougge |
| 001 | Implicit | 170908T023346Z | MD XF |
| 013 | GolfScript | 171120T164401Z | Marcos |
| 001 | Husk | 171120T163357Z | Mr. Xcod |
| 015 | dc | 171120T162924Z | ბიმო |
| 004 | Aceto | 171120T155102Z | qqq |
| 191 | LOLCODE | 171107T161840Z | qqq |
| 015 | Triangular | 170615T193349Z | MD XF |
| 022 | dc | 171031T181325Z | brhfl |
| 049 | Acc!! | 161221T051013Z | DLosc |
| 036 | TSQL | 171023T153347Z | WORNG AL |
| 023 | Haskell | 170110T160943Z | user3389 |
| 006 | Common Lisp | 170717T054046Z | ceilingc |
| 001 | Braingolf | 170717T143814Z | Mayube |
| 081 | Plain English | 170628T025008Z | Jasper |
| 039 | Common Lisp | 170709T200122Z | Renzo |
| 010 | Excel VBA | 161228T195203Z | Taylor R |
| 003 | MY | 170628T022043Z | Adalynn |
| 020 | Python 3 | 161221T113349Z | Dillanm |
| 017 | Fourier | 170528T120649Z | Beta Dec |
| 023 | tcl | 170108T013708Z | sergiol |
| 018 | C GCC | 161220T061027Z | betseg |
| 018 | C | 161222T060815Z | Albert R |
| 040 | BrainFlak 40 Bytes | 161220T151601Z | Riley |
| 001 | APL Dyalog APL | 161220T071108Z | Adá |
| 016 | Scala | 170114T093805Z | jaxad012 |
| nan | 161222T222447Z | user1893 | |
| 019 | Ruby | 170110T093457Z | G B |
| 024 | Symbolic Python | 170107T221238Z | FlipTack |
| 020 | Befunge93 | 161225T042026Z | osuka_ |
| 015 | MATLAB + Octave | 161230T000705Z | Tom Carp |
| 007 | Pushy | 161220T143906Z | FlipTack |
| 008 | Excel | 161222T234442Z | Anoplexi |
| 009 | MS Excel | 161228T191747Z | Taylor R |
| 041 | Piet | 161220T195850Z | Mike Buf |
| 040 | C# | 161226T143713Z | Horv |
| 023 | C | 161225T212905Z | Steadybo |
| 036 | /// | 161221T131131Z | Cedric R |
| 071 | Factor | 161224T203259Z | cat |
| 1920 | GNU Sed | 161224T071229Z | Claire C |
| 013 | Python 3 | 161224T070703Z | Frosty-n |
| 013 | Hexagony | 161221T015908Z | FryAmThe |
| 026 | Python 2 | 161224T000554Z | AvahW |
| 040 | BrainFlak | 161220T222801Z | Wheat Wi |
| 028 | Math++ | 161220T153738Z | SuperJed |
| 009 | JavaScript ES6 | 161220T055717Z | ETHprodu |
| 065 | Turing Machine code | 161220T154107Z | SuperJed |
| 014 | JavaScript ES6 | 161223T154642Z | Cedric R |
| 014 | GNU sed | 161220T064404Z | Jordan |
| 001 | Actually | 161220T060047Z | user4594 |
| 011 | TIBasic | 161223T005527Z | Julian L |
| 006 | MATL | 161220T102009Z | Luis Men |
| 201 | COW | 161220T171300Z | Gabriel |
| 868 | MarioLANG | 161222T134938Z | Cedric R |
| 023 | Python 3 | 161222T022009Z | Cormac |
| 004 | Stacked | 161221T223352Z | Conor O& |
| 017 | awk | 161221T211134Z | James Br |
| 023 | brainfuck | 161221T164425Z | Mitch Sc |
| 004 | OCaml | 161221T191510Z | shooqie |
| 049 | Go | 161221T043105Z | Eric Lag |
| 037 | Javascript | 161221T152408Z | Ostbulle |
| 009 | F# | 161220T100805Z | Stefan |
| 008 | QBIC | 161220T061235Z | steenber |
| 011 | Java 1.8 | 161220T133619Z | xenia |
| 015 | C# | 161220T075259Z | adrianmp |
| nan | BotEngine | 161221T111725Z | SuperJed |
| 023 | Batch | 161221T103336Z | Neil |
| 009 | Gema | 161221T092607Z | manatwor |
| 057 | Python 2 | 161221T042340Z | Ken Y-N |
| 024 | Clojure | 161220T221629Z | Carcigen |
| 022 | GameMaker Language | 161220T230559Z | Timtech |
| 008 | TIBasic | 161220T225745Z | Timtech |
| 013 | x86_64 machine language on Linux | 161220T213155Z | ceilingc |
| 038 | PHP | 161220T210404Z | Titus |
| 012 | V | 161220T161840Z | nmjcman1 |
| 022 | Forth | 161220T202357Z | zeppelin |
| 023 | Clojure | 161220T200042Z | NikoNyrh |
| 022 | Vim | 161220T095201Z | xenia |
| 036 | Jellyfish | 161220T173206Z | Zgarb |
| 043 | SAS Macro Language | 161220T172927Z | J_Lard |
| 010 | Cubix | 161220T061540Z | ETHprodu |
| 018 | Javascript | 161220T164033Z | BookOwl |
| 004 | PARI/GP | 161220T162845Z | alephalp |
| 016 | PHP | 161220T162830Z | Alex How |
| nan | Loader | 161220T155747Z | SuperJed |
| 011 | Befunge | 161220T132623Z | James Ho |
| 004 | Wonder | 161220T142336Z | Mama Fun |
| 6410 | Stack Cats | 161220T135748Z | Sp3000 |
| 004 | Mathematica | 161220T120708Z | Martin E |
| 028 | Mathematica | 161220T113507Z | Greg Mar |
| 024 | Octave | 161220T112932Z | user4180 |
| 003 | WolframAlpha | 161220T112744Z | Adá |
| 005 | Pyke | 161220T111714Z | Blue |
| 008 | ><> | 161220T102848Z | Martin E |
| 025 | R | 161220T102658Z | JAD |
| 004 | Octave | 161220T091708Z | Stewie G |
| 004 | Matlab | 161220T091617Z | pajonk |
| 008 | Labyrinth | 161220T085938Z | Martin E |
| 009 | Perl | 161220T080626Z | Dom Hast |
| 009 | Retina | 161220T074648Z | Martin E |
| 001 | CJam | 161220T081503Z | Martin E |
| 010 | Labyrinth | 161220T080426Z | Martin E |
| nan | 161220T072338Z | Brad Gil | |
| 003 | 05AB1E | 161220T071715Z | Emigna |
| 001 | J | 161220T071531Z | Adá |
| 004 | Mathematica | 161220T071023Z | Greg Mar |
| 006 | Haskell | 161220T070204Z | nimi |
| 001 | Jelly | 161220T055524Z | Jonathan |
| 002 | Pyth | 161220T061233Z | Jonathan |
| 002 | Japt | 161220T061018Z | ETHprodu |
| 010 | Ruby | 161220T061010Z | G B |
| 014 | Clojure | 161220T055326Z | clismiqu |
| 017 | Python 2 | 161220T055940Z | Dennis |
Malbolge Unshackled, 126 119 bytes
(=<A:#>=<l4981x543210/L-,+*)('&%$#"!~a`{:yxwv$tWVq0/.-,+*)(gfedcba`_^|\?TSXWVUTSRQPONMLEDIHGFEDCBA@?>=<;49816543210/.L9
This program assumes that the input will not have leading zeros. Also works with standard Malbolge. At least one other answer has used this requirement, so I guess this is fine. Obviously, if leading zeros are forbidden, the challenge becomes very easy, just check if the first character is a - or a 0, and output -1, 0 or 1.
Normalized code and explanation:
jppopjooo
/poopjooo
ooooioooo <- Write the first char into one of the cells, and jump on that value
ooooooooo
ojjoioooo
vojjoiiii
iiiiioooo <- If -, do some data jumps and go somewhere else
If 0, do one extra nop and go somewhere else
Otherwise, the jump will land on one of the i
in order to regroup them
oooooo<oj <- Start here if -, print it and do some crazyops to obtain 5
ppooooooo (any value would work)
ooooooppo <- Start here otherwise, transform the digit contained
ooooooooo within the accumulator into a 1
ooooopoop
ooooooooo
<v <- Start here if 0, print whatever the accumulator has
(0 or 1, the minus was already printed previously if necessary)
Bespoke, 110 bytes
seen a-n-y signs?i do sign viewing
IT OOOPENED UP MY EYES
clumsily done dancepop allusion(granted)and cringe-y
If the input is 0, it is outputted as-is; otherwise, 0 < n is calculated, then the result is added to itself and decremented, giving 1 if n is positive and -1 if n is negative.
Desmos, 12 bytes
f(x)=sign(x)
This is, of course the obvious solution, just use a built-in, but it's not very exciting. So I made this (15 bytes):
g(x)=2/(1+9^{-9x})-1
Which is a logistic function that is so steep that already at x = -1 and x = 1 it rounds off to the sign of x. It is important to note, this function does not work if the values are non-intigers, since near 0, this function gives a value between -1 and 1 as it interpolates between to switching of signs.
This function can be even further golfed to use the built-in error function like this:
h(x)=erf(9x)
Which gives us the same score as using the built-in, 12 bytes, despite not using it.
SAKO, 44 bytes
1)CZYTAJ:N
DRUKUJ(1,0):SGN(1,N)
STOP1
KONIEC
It just reads the input to variable N and prints 1 × sgn N.
YASEPL, 22 bytes
=b$!a']!$a*+%*a!a`1/b<
works the same as my jBasher2 solution, uses \$a×((2a+1)\text{ mod } 2)\$ for an abs function, uses \$\frac{a}{\left|a\right|}\$ to determine the sign.
jBasher2, 172 bytes
create a with type number
ask for input
set that to a
spawn 1
if a != 0
multiply 2 by a
add that by 1
modulo that by 2
multiply that by a
endif
divide a by that
output that
it uses the equation \$ a×((2a+1)\text{ mod }2) \$ as a replacement for an abs function, because jBasher2 does not have an abs function.
awk
fully POSIX-compliant awk solution
function __(_) { return (-!!_)^(_ < !_) }
-3.00 -1 3.00 1
-2.75 -1 2.75 1
-2.50 -1 2.50 1
-2.25 -1 2.25 1
-2.00 -1 2.00 1
-1.75 -1 1.75 1
-1.50 -1 1.50 1
-1.25 -1 1.25 1
-1.00 -1 1.00 1
-0.75 -1 0.75 1
-0.50 -1 0.50 1
-0.25 -1 0.25 1
0.00 0
Swift, 23 bytes
let s={($0+0).signum()}
There is absolutely nothing interesting about this.
COBOL (GNU), 68 bytes
S.
SET O TO 0
IF X > 0
SET O TO 1
ELSE IF X < 0
SET O TO -1
END-IF.
floor, 39 bytes
f:n->floor(n/(n*n+1))-floor(-n/(n*n+1))
takes an integer \$n\$ as input and computes \$ \left \lfloor \frac{n}{n^2+1} \right \rfloor - \left \lfloor -\frac{n}{n^2+1} \right \rfloor \$
Explanation
floor only supports basic arithmetic operators and the floor-function.
This function exploits the behavior that the floor function returns -1 if \$x\in (-1,0)\$ and 0 if \$x\in[0,1)\$.
To map the input number \$n\$ to the interval \$(-1,1)\$ without changing its sign, it is divided by the positive number \$n^2+1\$ which is guaranteed to have a larger absolute value than \$n\$
Implementation:
To run the program, execute the Python-script with the arguments
-f <source-file> -- <input-number>
Desmoslang, 8 Bytes
\sgn(IOT
That feeling when Stack doesn't accept your answer because it's too golfed.
Regex (Generic), 4 bytes
-?x?
Try it online! - GNU ERE
Try it online! - ECMAScript
Takes its input in unary, as an optional - sign followed by a string of x characters, the count of which represents the absolute value of the number. As such, it is not bijective unary, as zero can be represented in two ways. The regex works with both; it will return - from an input of - (effectively \$-0\$ from an input of \$-0\$), but since \$-0=0\$, this seems acceptable.
Regex (Generic), 2 bytes
.?
Try it online! - GNU ERE
Try it online! - ECMAScript
Takes its input in bijective signed unary. A nonnegative number is a string of x characters, and a nonpositive number is a string of o characters. The the length of the string is the absolute value of the number.
Lua, 46 45 38 33 32 26 bytes
load"return-1+2/(0^...+1)"
-6 bytes by using load instead of function, thanks to Jo King
Lua has no sign() built-in, and has a strict type system, so things like (n>0)-(n<0) can't be done concisely – its boolean type can't simply be cast to a numerical type.
This version works properly on all integer values and all floating point values.
- If
nis negative,0^n+1yields the valueinf, which then becomes zero when2is divided by it. Subtract1and this is-1. - If
nis zero,0^n+1yields2, becoming1when2is divided by it. Subtract1and this is0. - If
nis positive,0^n+1is1, becoming2when2is divided by it. Subtract1and this is1.
Other languages identified so far in which this works:
- Io - Try it online! - might be optimal; beats the Io answer by 6 bytes
- Zsh - Try it online! - ties with roblogic's answer, but returns a floating point
-1. - R - Try it online! - beats Robin Ryder's no-builtin answer by 5 bytes, but the builtin beats it by 4 bytes: Try it online!
- JavaScript - Try it online!, but ETHproductions's non-builtin answer beats it by 2 bytes, and the builtin beats it by 6 bytes: Try it online!
- Octave - Try it online! - ties with Tom Carpenter's no-builtin answer, but the builtin beats this by 10 bytes: Try it online!
Previous 38 byte version – works properly on all integer values, as asked for by this challenge. Fails for floating point inputs greater than \$0\$ and less than or equal to \$0.1\$:
function(n)return n//math.abs(n-.1)end
Try it online! - or 33 bytes with load: Try it online!
Previous 43 byte version – works for all floating point values, but fails for integers with an absolute value greater than \$2^{31.5}\$:
function(n)return n/(n*n+#{[0^n]=0})^.5 end
Try it online! - or 41 bytes with load and no global variable usage: Try it online!
Previous 45 byte version – works for all integers and floating point values:
function(n)return n/math.abs(n+#{[0^n]=0})end
Try it online! - or 42 bytes with load: Try it online!
Previous 46 byte versions:
function(n)return n>0 and 1 or#{[n+1]=0}-1 end
function(n)return n<0 and-1 or 1-#{[n+1]=0}end
The versions ranging to 43 to 46 bytes use a tip I have explained here, which is a basically a workaround for Lua's strong typing. Without that trick it would have been 48-49 bytes:
function(n)return n==0 and 0 or n/math.abs(n)end
function(n)return n~=0 and n/math.abs(n)or 0 end
function(n)return n/math.abs(n+0^math.abs(n))end
function(n)return n>0 and 1 or n<0 and-1 or 0 end
function(n)return n<0 and-1 or n>0 and 1 or 0 end
Binary-encoded Golfical, 17 bytes
The binary-encoded version of Golfical can be converted back to the original image using the Encoder utility included in the github repository, or run directly by using the -x flag
Hexdump of binary encoding:
00 40 03 15 14 14 23 17 14 26 02 01
17 1c 00 01 17
Original program image:

Image magnified 50x with RGB colors labelled:

I'd probably save a few bytes here if the language had an absolute value function (or a native sign function)
Piet + ascii-piet, 19 bytes (4×6=24 codels)
tabraF krbtKbks?Tbb
(previous record: 40 codels/ascii-piet bytes)
An approach involving a CC+ turned out to be the most space-efficient compared to branchless ones.
inN [n]
dup 1 ! > ! [n !(n>0)]
CC+ [n] Switch CC if n is 0 or less (follow upper path)
otherwise follow lower path
Upper path:
! 1 - [(n=0)-1] 0 if n is zero, -1 if negative
Lower path:
1 [n 1] Simply push 1
outN Print the top number and halt
Some candidates I tried include:
- cost 15 (cost is 1 per command, plus pushed numbers minus 1)
1 ! inN dup 1 ! [0 n n 0]
> [0 n n>0]
3 1 roll > [n>0 0>n]
- outN [] Print (n>0)-(0>n)
- cost 16, tries not to use roll and instead uses a weird division trick.
-1 / positiveis -1,-1 / 0is division by zero,-1 / -1is 1, and-1 / -2..is 0. I use+after/to make-1 / 0case give -1, and then do%3-1to map each case to the correct output.
1 2 - inN 1 - [-1 n-1]
/ + [x] x = -1/(n-1) as described above
3 % 1 - outN Print the correct ouptut
- cost 16, uses a
>and!instead of two>s. The formula in this case is(n>0)*2 + (n=0) - 1.
inN dup ! [n n=0]
2 1 roll [n=0 n]
1 ! > [n=0 n>0]
dup + + 1 - outN Calculate and print the result of the formula
Trilangle, 21 bytes
?\<'1(0@'^\.!_@>'0.(#
Try it in the online interpreter!
Unfolds to this:
?
\ <
' 1 (
0 @ ' ^
\ . ! _ @
> ' 0 . ( #
Conceptually equivalent to this C code:
#include <stdio.h>
int main() {
int x;
scanf("%i", &x);
if (x < 0) {
puts("-1");
} else if (x > 0) {
puts("1");
} else {
puts("0");
}
}
but that really doesn't do justice to how dense the control flow is.
As with every Trilangle program, control flow starts in the north corner heading southeast, on the red path in the image above. It reads the following instructions:
?: Read an integer from stdin and push it to the stack\: Redirect control flow<: Branch on sign
If the value read in was negative, control flow continues on the green path:
>: Redirect control flow'0: Push a 0 to the stack.: No-op(: Decrement. Because the push-int instruction can only push a single digit, the easiest way to get -1 is'0((push 0 and decrement) or'0~(push 0 and bitwise NOT). Either works here; I chose(arbitrarily.#: Skip the next character (the/).: Another no-op!: Print the top of the stack_: No-op in this direction@: End program
If the value read in was positive or zero, the IP follows the blue path:
(: Decrement. 0 is now negative and positive values are still non-negative.^: Branch on sign again
If the value read in was initially positive, it takes the yellow path:
_: Redirect control flow'1: Push a 1 to the stack\: No-op in this direction.: No-op!: Print the top of the stack@: End program
If the value read in was initially zero, it follows the magenta path. This does a bit more work than necessary to avoid interfering with the other paths:
'1: Push a 1 to the stack(: Decrement. Great, we've turned zero into zero.\: Redirect control flow (moving towards the print statement)': Oh no, another push instruction? But we already have a zero!0: Push another zero I guess.\: Redirect control flow, merging with the green path.!_@: Same as above.
There are other ways I could achieve the same result, e.g.:
?\<)2(.@'^\.!_@>'0(.#
but that has basically the same control structure, and is still 21 bytes. I'm not certain it's impossible to do shorter, but I wouldn't know how.
Thunno, 2 bytes
za
Built-in. Works on lists.
Thunno D, 3 bytes
ZA,
Does \$ x \div |x| \$, which gives \$0\$ for \$0\$.
A0A0, 18 bytes
I0L0V0O0
G-1G-1G-1
Explanation:
I0 L0 V0 O0
I0 ; Reads number as input, stored in the operand
L0 ; Compare the operand against 0
V0 ; The operand, value is placed in the next instruction
O0 ; Ouputs the number of the operand
Microscript II, 21 bytes
N(s""+K45=("-1"ph)!_)
todo: add an explanation
GNU AWK, 15 bytes
sub(/\w+/,!!$0)
The efforts in golfing James Brown's code brought me to this answer. It is exclusive to GNU AWK, due to the use of \w.
AWK, 16 bytes
!$0||$0=/-/?-1:1
This works in traditional AWK.
Julia, 4 bytes
sign
trivial built-in but it was missing here
Julia (without sign)
round∘tanh 12 bytes
x->tanh(99x) 12 bytes
x->tanh(9x) 11 bytes (input must be Float32)
tinylisp, 32 bytes
(d F(q((X)(i X(i(l X 0)(q -1)1)0
Since there are no negative number literals in tinylisp, they have to be passed in using subtraction.
tinylisp, 21 bytes
(q((N)(s(l 0 N)(l N 0
Anonymous function that takes a number and returns a number. Try it online!
Ungolfed/explanation
(load library) ; Load the library to get ungolfed aliases for builtins
(lambda (N) ; Anonymous function of one argument
(sub2 ; Take the difference of
(less? 0 N) ; 1 if N is positive, 0 otherwise
(less? N 0))) ; 1 if N is negative, 0 otherwise
K (ngn/k), 4 bytes
0 1'
Uses sortedList' as binary search.
0 1'do a binary lookup on0 1; if the input is0, it will match the first index, returning0; if larger than0, it'll match to the1value at the second index, returning1. If the input is smaller than0, it will return-1, indicating that the input is less than each value in the sorted list.
Python 3.8, 47 bytes
print(1if(n:=int(input()))>0else-1if n<0else 0)
BitCycle -U, 8 bytes
?v
/=
>!
Explanation
BitCycle's -U flag represents signed integer inputs as follows:
- Positive integer \$N\$: a stream of \$N\$ 1's
- Negative integer \$-N\$: 0 followed by a stream of \$N\$ 1's
- Zero: 0
So all we need to do is output the leading 0 (if any) and the first 1 (if any), and discard the rest of the 1's.
The switch device (=) is very convenient for this task. The first bit that hits a switch passes straight through, but it also activates the switch in one of two directions: a 0 bit turns the switch into {, which redirects all subsequent bits westward, while a 1 bit turns the switch into }, which redirects all subsequent bits eastward.
In our program, we direct the input from the source ? into the switch =, moving southward. The first bit (either the leading 0 or a 1 if there is no leading 0) goes straight through to the sink ! and is output. Then:
- If the first bit was a
1(positive number), the switch activates as}, which redirects the remaining bits off the playfield. - If the first bit was a
0(non-positive number), the switch activates as{, which redirects the remaining bits westward into the splitter/. This device sends the first bit that hits it southward, where it is redirected into the sink and output. All subsequent bits that reach the splitter pass through it and off the playfield.
Pxem, Contents: 0 bytes + Filename: 33 25 bytes
- Filename(unprintables are escaped):
1._.c.w\001.r.yXX-.a.p.d.a.n - Content is empty.
Usage
Give an integer from STDIN. The result is output from stdout, with no LF termination.
How it works
XX.z
# Prepare character 1 at this point
.aXX1.z
# integer input is pushed
.a._XX.z
# duplicate, and is it non-zero?
.a.c.wXX.z
# then come here
# also \001.r is an idiom to push zero:
# actually "n=pop;push(int(random()*n))"
# where 0<=random()<1
# because filename cannot have null character
# don't be afraid of such binary for code golf
.a\001.rXX.z
# is input less than zero?
# DOT-y to DOT-a is:
# while size<2 OR pop>pop; do something; done
.a.yXX.z
# if so, push hyphen so string "-1" is made
.aXXXX-.z
.a.aXX.z
# at this point DOT-y popped two items: zero and input integer
# so no worry about garbages
# print the string and exit
# .p is actually: while !empty; do printf "%c", pop; done
.a.p.dXX.z
# if input is zero, come here
# .n is printf "%d", pop
# OBTW the "1" will on stack, but it's not matter,
# because it is ignored when program ends
.a.a.n
Previously
- 33bytes of filename:
._.c.w.c00.-.-.z-1.p.d.a1.o.d.a.n
x86, 9 bytes
97 xchg eax, edi
99 cdq
92 xchg eax, edx
39 C2 cmp edx, eax
7E 01 jng $+3 ; --,
40 inc eax ; |
C3 ret ; <-'
No one posted this
Vyxal, 1 byte
±
Nothing special, just a built-in, but nobody else had posted it yet, so I figured I might as well.
No built-in, 72 bytes
Thanks to @Bubbler for saving 5 bytes.
ȧ/
Does |x| / x. In Vyxal, 0 / 0 returns 0 instead of a divide by zero error, so this works.
R, 21 bytes, no builtin
x=scan();x/abs(x^!!x)
Takis input from STDIN. Avoids the builtin sign. This comes out 4 bytes shorter than JAD's solution with if. We cannot use directly x/abs(x) since we would divide by 0 when x=0.
After coercion to integer, !!x will be equal to 1 for all input except 0 (when it is equal to 0). Since 0^0=1, this trick allows to avoid dividing by 0:
- For nonzero input, it is equivalent to
x/abs(x^1), giving +1 or -1 - For
x=0, it is equivalent tox/1, giving 0
x86_64 machine code - 26 24 bytes
This is callable function, input in r8 output in rax.
-3 bytes using cbw instruction is 2 bytes instead of movzx rax, al is 4 bytes.
0000000000400080 <output_the_sign>:
400080: 48 31 c0 xor rax,rax
400083: 4d 85 c0 test r8,r8
400086: 74 11 je 400099 <output_the_sign.done>
400088: 0f 95 c0 setne al
40008b: 66 98 cbw
40008f: 4c 89 c2 mov rdx,r8
400092: 48 c1 fa 1f sar rdx,0x1f
400096: 48 09 d0 or rax,rdx
0000000000400099 <output_the_sign.done>:
400099: c3 ret
BRASCA, 8 bytes
,'/-1$%n
Explanation
, - Reverse the stack to take the first character from input
'/- - Subtract it by 47
1$% - 1 % that value
n - And output it
Python - 23 bytes
print((n>0)*2+(n==0)-1)
This checks if n is greater than 0 (in which case it outputs 2 for the next step), then if it is equal to 0 (in which case it outputs 1) and then subtracts 1, leaving us with -1 if n < 0, 0 if n == 0, and 1 otherwise.
(Yes, the double brackets are necessary, I have checked.)
Java, 12 bytes
Long::signum
Using Long instead of Integer saves 3 bytes.
Stax, 2 bytes
:+
Stax has a sign builtin. Kind of boring. Here's a solution that uses clamp instead
Stax, 4 bytes
U1:c
U push -1 to stack
1 push 1 to stack
:c clamp input between -1 and 1
Mornington Crescent, 2060 2054 1246 bytes
The improved solution is here!
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Parsons Green
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take District Line to Acton Town
Take District Line to Hammersmith
Take Circle Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take District Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Holborn
Take Central Line to Holborn
Take Central Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take District Line to Acton Town
Take District Line to Parsons Green
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Central Line to Holborn
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Holborn
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Leicester Square
Take Northern Line to Leicester Square
Take Northern Line to Mornington Crescent
The algorithm:
- Parse an integer out of the string provided as input at Parsons Green.
- Take the two's complement of the result of step 1 at Notting Hill Gate.
- Compute the value of 1 by dividing the result of step 2 by itself.
- Take the two's complement of 1 to get -2.
- Take the greater of -2 and the result of 2.
- Take the two's complement of the result of step 5.
- Parse an integer out of a string that contains no integer at Parsons Green, yielding 0.
- Take the two's complement of 0 to get -1.
- Take the greater of -1 and the result of step 6.
- Output the result. In conclusion, the program clamps the integer between the values of -1 and 1, similarly to other solutions.
Old solution:
Took me the better part of two days to figure it out, but I think I have it. The program does not function correctly if faced with -0 or 03 as inputs, so its preconditions are such that there are no leading zeros in the input and that -0 is invalid as well.
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Northern Line to Bank
Take Circle Line to Bank
Take Circle Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Victoria
Take Victoria Line to Seven Sisters
Take Victoria Line to Green Park
Take Victoria Line to Green Park
Take Piccadilly Line to Russell Square
Take Piccadilly Line to Russell Square
Take Piccadilly Line to Acton Town
Take District Line to Acton Town
Take District Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Victoria
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Cannon Street
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Upminster
Take District Line to Upney
Take District Line to Cannon Street
Take District Line to Upney
Take District Line to Cannon Street
Take District Line to Upney
Take District Line to Hammersmith
Take Circle Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take District Line to Upminster
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take District Line to Acton Town
Take District Line to Upney
Take District Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Acton Town
Take District Line to Acton Town
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take District Line to Barking
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Barking
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent
The algorithm:
- Get the first character of the input, which should be
-if negative,0if zero, or any other digit1through9if positive. - Convert to ASCII. Now the program should have
45if the input was negative,48if the input was zero, and an integer between49and57if the input was positive. - Take the bitwise NOT of the ASCII integer. Now the program should have
-46if the input was negative,-49if the input was zero, and an integer between-50and-58if the input was positive. - Add 49 to the previous integer. Now the program should have
3if the input was negative,0if the input was zero, and an integer between-1and-9if the input was positive. - Complete integer division by 3. Now the program should have
1if the input was negative,0if the input was zero, and an integer between-1and-3if the input was positive. - Take the maximum function of the previous integer and -1 (taking whichever is larger). Now the program should have
1if the input was negative,0if the input was zero, and-1if the input was positive. - Take the bitwise NOT of the previous integer. Now the program should have
-2if the input was negative,-1if the input was zero, and0if the input was positive. - Add one to the previous integer. Now the program should have
-1if the input was negative,0if the input was zero, and1if the input was positive. We are done.
Overall, a very rewarding but tiring experience.
EDIT, -6 bytes: Changed Embankment to the shorter Barking.
COW, 153 75 bytes
oomMMMmoOMoOmoOMMMMOOmoOOOOMOomOoMoOmOomOoMOOMOomoOmoOMMMOOOmooMMMmoomoOOOM
COW can't compare numbers so N is stored in two cells, (if N is not 0) in turns one will be increased and the other decreased. When eventually one of them reaches 0, the loop will stop.
The sign will be in the next cell.
Detailed Explanation:
[0]: N to be incr [1] = -1 [2]: N to be decr [3] = 1
i=>+>= ; Read N in [0], set [1] = 1 and copy it to [2]
[ ; Loop while [2] is non-zero
>°-<+<< ; Set [3] = -1, increase [2] then point to [0]
[ ; Loop while [0] is non-zero
->>=° ; Decrease [0], point to [2] copy in register and set it to 0 (to exit)
] ;
= ; Paste from register to [2]
] ; When exiting the poited cell could be [0] or [1], in either case...
>o ; ...move one right and it would contain the correct output
moo ] mOo < MOo - OOO ° OOM i
MOO [ moO > MoO + MMM = oom o
I've tried other permutations of memory cells but this seems the best.
Setting [3] (a constant) inside the loop is needed to manage the case N=0.
8th, 40 3 bytes
With 8th is quite simple to get the sign of N, which is left on TOS
sgn
Testing and Output
ok> 42 sgn .
1
ok> -42 sgn .
-1
ok> 0 sgn .
0
The following code, as an alternative, has the same behaviour of 8th's builtin word n:sgn
: f dup 0; 0 n:> if 1 else -1 then nip ;
Explanation of word f
: f \ n -- -1|0|1
dup \ Duplicate input
0; \ Check if number is 0. If true, leave 0 on TOS and exit from word
0 n:> \ Check if positive
if 1 \ Return 1 if positive
else -1 \ Return -1 if negative
then
nip \ Get rid of input
;
Testing and Output
ok> 42 f .
1
ok> -42 f .
-1
ok> 0 f .
0
asm2bf, 91 bytes
Takes input as a string on the input (i.e. 1234). Assumes no leading zeros.
in_ r1
mov r2,r1
eq_ r2,.0
eq_ r1,.-
jnz r1,%m
jnz r2,%z
out .+
end
@m
out .-
end
@z
out .0
J, 2 bytes
%|
Explanation
It's a hook, so I'll explain it as y%(|y).
(|y) NB. Magnitude of y.
y% NB. y/abs(y)
Oh, yes, I am learning J. I want to golf in android and building my own golfing language is hard, so I started learning J.
ArnoldC, 498 bytes
IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP 0
GET YOUR ASS TO MARS n
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
HEY CHRISTMAS TREE m
YOU SET US UP 0
GET TO THE CHOPPER m
HERE IS MY INVITATION n
GET UP n
GET UP 1
ENOUGH TALK
GET TO THE CHOPPER m
HERE IS MY INVITATION m
GET DOWN 1
I LET HIM GO m
GET DOWN 1
ENOUGH TALK
GET TO THE CHOPPER m
HERE IS MY INVITATION m
GET UP 1
I LET HIM GO m
ENOUGH TALK
TALK TO THE HAND m
YOU HAVE BEEN TERMINATED
Explanation
IT'S SHOWTIME
# n = 0
HEY CHRISTMAS TREE n
YOU SET US UP 0
# n = input
GET YOUR ASS TO MARS n
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
# m = 0
HEY CHRISTMAS TREE m
YOU SET US UP 0
# m = n + n + 1
GET TO THE CHOPPER m
HERE IS MY INVITATION n
GET UP n
GET UP 1
ENOUGH TALK
# m = ((m - 1) % m) - 1
GET TO THE CHOPPER m
HERE IS MY INVITATION m
GET DOWN 1
I LET HIM GO m
GET DOWN 1
ENOUGH TALK
# m = (m + 1) % m
GET TO THE CHOPPER m
HERE IS MY INVITATION m
GET UP 1
I LET HIM GO m
ENOUGH TALK
# print m
TALK TO THE HAND m
YOU HAVE BEEN TERMINATED
Desmos, 12 bytes
f(x)=sign(x)
or $$f\left(x\right)=\operatorname{sign}\left(x\right)$$ Try It On Desmos!
dc, 7 bytes
?dd*v/p
Input on stdin, output on stdout. (There may also be spurious output to stderr, which should be ignored, as usual.)
This uses the formula $$\frac{\left\lfloor\sqrt{n^2}\right\rfloor}n$$
plus the fact that if you divide by 0 in dc, it leaves the 0 at the top of the stack.
(If you try this out, note that negative numbers are written in dc with an initial _ instead of -, since - is only used for the two-argument subtraction operation.)
Symja, 29 26 bytes
f(x_):=If(x==0,0,x/Abs(x))
-3 bytes to due porting the idea behind the Io answer.
Answer History
29 bytes
f(x_):=If(x<0,-1,If(x>0,1,0))
For some reason, my edit history didn't save this old approach.
Scratch 3.0, 9 blocks/44 bytes
For those who are tired of the old way of introducing these answers [I'm looking at you a'_' ...(ಠ ͟ʖಠ)], I'll put the ScratchBlocks Syntax first:
define f(n
set[r v]to(<(n)>(0)>-<(n)<(0
say(r
I decided to use a function instead of the old when gf clicked approach because that means I don't have to deal with having an ask() and wait next.
PowerShell, 22 21 bytes
[math]::sign("$args")
Boring built-in, calls the .NET function that does exactly what it says on the tin. Ho-hum.
Try it online!
-1 byte thanks to Veskah.
For 26 bytes however, we get the classic greater-than less-than equation
param($b)($b-gt0)-($b-lt0)
This, at least, has a little bit of logic and thought put into it. Try it online!
Best yet, though is 44 bytes, where we roll our own solution.
param($b)if("$b".indexof('-')){+!!$b;exit}-1
Here we take input $b, stringify it, take the .IndexOf('-') on it, and use it in an if clause. If the negative sign isn't found, this returns -1, which is truthy in PowerShell, so we turn $b into a Boolean with !, invert the Boolean with another !, cast it as an int with +, leave it on the pipeline, and exit. This turns a positive integer (which is truthy) into $false, then $true, then 1, while turning 0 into $true, then $false, then 0. Otherwise, the .IndexOf returned 0 (meaning it was the first character in the string), which is falsey, so we skip the if and just place a -1 on the pipeline. In either case, output via implicit Write-Output happens at program completion. Try it online!
Python 3, 26 25 bytes
An interesting way to approach this problem using the irregularity of Python 3 hash function.
lambda x:x/abs(~hash(~x))
Explanation
The big idea is to return x/abs(x). However, this causes division by 0 if x is 0.
hash(i) (where \$i\$ is an integer) returns \$i\$ most of the time, with the exception of hash(-1) returning \$-2\$. Thus ~hash(~x) (where ~ denotes bitwise negation) evaluates to:
- If
x != 0:~hash(~x) == ~~x == x - If
x == 0:~hash(~0) == ~hash(-1) == ~(-2) == 1
Thus instead of dividing by abs(x), we divides by abs(~hash(~x)) which can never be 0.
Note: This will not work for large integers (\$\ge2^{61}\$), since hash of long integer is calculated differently.
Gol><>, 8 bytes
I:SA:?,h
How it works
I:SA:?,h
I Input as number; [n]
: Duplicate; [n n]
SA Absolute value; [n abs(n)]
: Duplicate again; [n abs(n) abs(n)]
? Pop one; if it is zero, skip next command
, Nonzero n: Divide n by abs(n)
h Print top as number and exit
Gol><>, 11 bytes
I:0(qm$0)+h
How it works
I:0(qm$0)+h
I Input as number
: Duplicate top
0( Change top to "top < 0"
q If top is true...
m$ Push -1 and swap top two; the stack is [-1 x]
Otherwise, skip two commands (m$); the stack is [x]
0) Change top to "top > 0"
+ Add top two
h Print top as number and halt
Python 3, 30 bytes
Just here to share another solution.
lambda x:eval(f'x and {x}**0')
Explanation
lambda x: # Lambda function with the variable x
eval(f' {x}**0') # Raise x to the power of 0
x and # Since 0 ** 0 = 1, we prevent that
# by using logical and.
naz, 64 bytes
9a5m2x1v3a2x2v1x1f1o0m1a1o0x1x2f1o0x1x3f1r3x1v1e3x2v2e0m1a1o0x3f
Explanation (with 0x commands removed)
9a5m2x1v # Set variable 1 equal to 45 ("-")
3a2x2v # Set variable 2 equal to 48 ("0")
1x1f1o0m1a1o # Function 1
# Output once, set the register equal to 1, and output again
1x2f1o # Function 2
# Output once
1x3f # Function 3
1r # Read a byte of input
3x1v1e # Jump to function 1 if the register equals variable 1
3x2v2e # Jump to function 2 if the register equals variable 2
0m1a1o # Otherwise, set the register equal to 1 and output
3f # Call function 3
F#, 140 bytes
open Checked
let s n=
if n=0 then 0
else
try
let mutable p=n
while p<>0 do
p<-p+1
-1
with| :? System.OverflowException->1
Basically, if the number is non-zero, keep adding 1 to it until you get either 0 (so the original value was negative) or an overflow (so the original value was positive).
That's all right, isn't it?
Canvas, 3 2 bytes
⤢÷
This might be the shortest solution without a builtin that does the problem for you (I'm looking at you, Jelly.)
Explanation:⤢÷ | *Full code*
÷ | Divide
| The input (implicit)
⤢ | By its absolute value
TIS -n 1 1, 57 bytes
@0
MOV UP ACC
ADD 998
SUB 998
SUB 998
ADD 998
MOV ACC ANY
The integral data type supported by TIS ranges from -999 to 999. Any value in input, code, or calculations is silently coerced (clamped) into that range (instead of truncation, overflowing, etc.).
So, by adding 998 to any number, then subtracting the same amount, it becomes 1 is it was positive, and stays untouched otherwise. We then do the same to coerce all negative numbers to -1.
We need to subtract across two separate operations, due to the coercion mentioned above.
If you are familiar with TIS-100, you will be used to a 3x4 array of computational nodes, however, this solutions only uses one such node, nominally taking input from above and giving it below.
Hexagony, 18 15 bytes
~.?>.)<<!!.&,.@
n > 0
~ . ?
. . . .
< . ! . .
, . @ .
. . .
n == 0
~ . ?
> . ) <
< . ! . &
. . @ .
. . .
n < 0
~ . ?
> . ) <
< ! . . .
, . @ .
. . .
Abuses the same EOF trick used in Jo Kings answer.
Sadly I currently don't have access to these neat visual tools used in other solutions.
Brain-Flak, 40 38 bytes
{<>(())<>{(([{}[]]))<>([{}])<>}}<>({})
A bit longer at 50 bytes, but here's a version that acts only on the top value of the stack, returning 0, -1 or 1 depending on the sign of the number.
({<({}([(())])){({}([{}([{}])]))}{}{}>{}(<()>)}{})
How it Works:
{ If number is not 0
<>(())<> Push 1 to the other stack as the sign
{ While number != 0
(([{}[]])) Push -(number+stack height) twice
<>([{}])<> Negate sign, alternating it between -1 and 1
} end while
}<>({}) Switch to other stack and force a 0 if the stack is empty
MachineCode, 26 bytes
31c085ff0f9fc0c1ef1f29f8c3
Requires the i flag for integer output. Input must be appended to the code on a separate line. This is equivalent to the C code (n>0)-(n<0). Try it online!
Alternatives with the same bytecount:
31c085ff0f95c0c1ff1f09f8c3- Try it online! Equivalent to the highest voted C submission.89f8c1ff1ff7d8c1e81f01f8c3- Try it online! Equivalent to this C code.
Brain-Flueue, 40 bytes
{([({})]){({}())<>([{}()()])<>}}(<>[]{})
Readable version
{
([({})])
{
({}())<>
([{}()()])<>
}
}
(<>[]{})
Hexagony, 16 bytes
...!/~.?.<.!1@.,
Not much smaller than the previous answer, but strangely elegant in comparison.
Expanded:
. . .
! / ~ .
? . < . !
1 @ . ,
. . .
Whitespace, 73 72 68 bytes
[S S S T N
_Push_1][S N
S _Duplicate_1][S N
S _Duplicate_1][T N
T T _Read_as_integer][T T T _Retrieve][S N
S _Duplicate_input][S N
S _Duplicate_input][N
T T N
_If_negative_jump_to_Label_NEGATIVE][N
T S S N
_If_0_jump_to_Label_ZERO][S N
T _Swap_top_two][T N
S T _Print_as_integer][N
N
N
_Exit][N
S S N
_Create_Label_NEGATIVE][S S T T N
_Push_-1][T N
S T _Print_as_integer][N
N
N
_Exit][N
S S S N
_Create_Label_ZERO][T N
S T _Print_as_integer]
Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Example runs:
Positive:
Command Explanation Stack Heap STDIN STDOUT STDERR
SSSN Push 1 [1] {}
SNS Duplicate top (1) [1,1] {}
SNS Duplicate top (1) [1,1,1] {}
TNTT Read STDIN as integer [1,1] {1:5} 5
TTT Retrieve at heap 1 [1,5] {1:5}
SNS Duplicate top (5) [1,5,5] {1:5}
SNS Duplicate top (5) [1,5,5,5] {1:5}
NTTN If neg.: Jump to Label_NEG [1,5,5] {1:5}
NTSSN If 0: Jump to Label_ZERO [1,5] {1:5}
SNT Swap top two [5,1] {1:5}
TNST Print top as integer [5] {1:5} 1
NNN Exit [5] {1:5}
Program stops with an error: Label does not exist
Try it online (with raw spaces, tabs and new-lines only).
Zero:
Command Explanation Stack Heap STDIN STDOUT STDERR
SSSN Push 1 [1] {}
SNS Duplicate top (1) [1,1] {}
SNS Duplicate top (1) [1,1,1] {}
TNTT Read STDIN as integer [1,1] {1:0} 0
TTT Retrieve at heap 1 [1,0] {1:0}
SNS Duplicate top (0) [1,0,0] {1:0}
SNS Duplicate top (0) [1,0,0,0] {1:0}
NTTN If neg.: Jump to Label_NEG [1,0,0] {1:0}
NTSSN If 0: Jump to Label_ZERO [1,0] {1:0}
NSSSN Create Label_ZERO [1,0] {1:0}
TNST Print top as integer [1] {1:0} 0
error
Program stops with an error: No exit defined
Try it online (with raw spaces, tabs and new-lines only).
Negative:
Command Explanation Stack Heap STDIN STDOUT STDERR
SSSN Push 1 [1] {}
SNS Duplicate top (1) [1,1] {}
SNS Duplicate top (1) [1,1,1] {}
TNTT Read STDIN as integer [1,1] {1:-5} -5
TTT Retrieve at heap 1 [1,-5] {1:-5}
SNS Duplicate top (-5) [1,-5,-5] {1:-5}
SNS Duplicate top (-5) [1,-5,-5,-5] {1:-5}
NTTN If neg.: Jump to Label_NEG [1,-5,-5] {1:-5}
NSSN Create Label_NEG [1,-5,-5] {1:-5}
SSTTN Push -1 [1,-5,-5,-1] {1:-5}
TNST Print top as integer [1,-5,-5] {1:-5} -1
NNN Exit [1,-5,-5] {1:-5}
Program stops with an error: Label does not exist
Try it online (with raw spaces, tabs and new-lines only).
Minecraft Functions (18w11a, 1.13 snapshots), 131 bytes
Uses a function named a in the minecraft namespace
execute if score @p n matches 0 run say 0
execute if score @p n matches 1.. run say 1
execute if score @p n matches ..-1 run say -1
"Takes input" from a scoreboard objective named n, create it with /scoreboard objectives add n dummy and then set it using /scoreboard players set @p n 8. Then call the function using /function a
Swift, 44 bytes
func s(i:Int)->Int{return i>0 ?1:i<0 ? -1:0}
Strange spacing around the ternary options, I know, but this was the shortest way.
SHELL ( 20 Bytes )
sed s/[1-9][0-9]*/1/
tests:
echo "789" | sed s/[1-9][0-9]*/1/
1
echo "-789" | sed s/[1-9][0-9]*/1/
-1
echo "0" | sed s/[1-9][0-9]*/1/
0
Stax, 2 bytes
:+
Explanation
Added for completeness. It is a builtin, but all built-ins starting with a colon in Stax is actually a macro defined using other Stax operations.
Internally it is defined as c0>s0<-, which is simply (x>0)-(x<0).
FORTRAN 77, 87 bytes
READ*,I
IF(I)1,2,3
1 PRINT*,-1
2 PRINT*,0
3 PRINT*,1
END
It is a nice use for the "harmful" arithmetic if statement. Unfortunately, this lovely feature was obsolete in Fortran 90 and posterior versions.
Curiously, gfortran can't handle with this arithmetic if, even if I save the file with .f extension. Therefore, I could not test this code.
Befunge-93 (PyFunge), 12 bytes
~"1"%90p1X.@
Note that the X can be anything (except a new line), as it gets written over during run-time. It's just easier for explanation
Similar to my other Befunge answer, but this time it mods the first character by the ASCII for 1 first, so that a positive first digit will turn into a no-op, leaving the 1 on the top of the stack:
~ Read the first *character* of input - either a digit or "-"
"1"% Mod the character by the ASCII value of 1. After this step, the character
is a '-' for negative numbers, '0' for 0, and small, unprintable
characters for positive numbers
90p Puts the character in the space with the X.
1 Pushes a 1
X 3 different options based on the character that was put here:
- Negative: Subtract the 1 from the implicit 0 to get -1
0 Zero: Push 0
Positive: A no-op, which leaves the 1 on top
. Prints out the top of the stack
@ Ends the program
Lua (51 Bytes)
n=tonumber(...) print(n<0 and -1 or n>0 and 1 or 0)
... is the variable that represents arguments in lua, tonumber(...) converts the first argument to a number.
also in lua a and b or c is a structure that returns b if a is truthy or c if a is falsy, you can nest this structure as well
Befunge 93, 14 13 bytes
Golfed off a byte by combining the 2 1s
1~50p :0`_.@.
This one is interesting, as it takes the first character of the number and alters the code accordingly.
~50p Stores the first character in the space (labeled <char> here)
1 <char> If the number is negative, it performs subtraction, giving 1 - 0 == -1
If it is 0, 0 is on top. If it is positive, a positive # will be.
:0`_ This checks the top number to see if it is positive.
.@ If it is <1, it is printed. (0 or -1)
1 @. Otherwise, the IP loops back harmlessly, and prints 1
Yabasic, 16 bytes
Anonymous function that takes input as a number, n, and output to STDOUT
input""n
?sig(n)
Functoid, 30 28 bytes
In functoid there is no support for negative integers since numbers are handled as Church numerals. This solution redefines numbers in a way that supports negative numbers (please refer to the explanation):
<|12K0K$BbB
r<@.1,"-"
)<@.([
Try it online! (Here is an input generator)
Explanation
The definition of negative numbers extends the Church numerals by simply introducing another lambda abstraction that encodes the sign of a number (the first argument, ie. x3). Here is how the numbers -2,-1,0,1,2 would look like in this notation:
Decimal number | extended Church numerals | absolute value as Church numeral
---------------+--------------------------+---------------------------------
-2 | λλλ(x3 (x2 (x2 x1))) | λλ(x2 (x2 x1))
-1 | λλλ(x3 (x2 x1)) | λλ(x2 x1)
0 | λλλ(x1) | λλ(x1)
1 | λλλ(x2 x1) | λλ(x2 x1)
2 | λλλ(x2 (x2 x1)) | λλ(x2 (x2 x1))
Now for the explanation of the above code: The characters < will change the direction to left, this saves us four bytes but makes it more difficult to read.. Here's how the code would look like without doing this:
BbB$K0K21|
@.1,"-"r<
@.([)<
The combinator BbB ensures that K0 and K2 get grouped as one expression each, here's the more verbose code:
$(K0)(K2)1|
@.1,"-"r<
@.([)<
Okay now it's quite readable: First $ will apply the input so we'll have a sign-extended Church numeral as current expression. Applying K0 (constant 0) will evaluate to KK0 (which will "swallow" the next two arguments) in the case of a negative number, in the case of a non-negative number it simply vanishes. In the case of a positive number we'll have K2 which will swallow the argument 1 and else we'll finally get 1.
Summing up the function $(K0)(K2)1 gives the following numbers (regular Church numerals):
if input < 0:
return 0
elif input > 0:
return 2
else:
return 1
The command | will set the direction down iff the current expression evaluates to 0 and up in the other case.
- The second line is thus only relevant if the input was negative and it simply prints
-1and terminates - In the other case (ie. hitting the third line) it applies the current expression to
[which decrements it by 1, prints the expression (as a numeral) and terminates
Disclaimer
It might look like the above extension was done just to make this task easier, however this is not the case. In fact most definitions in the untyped (or rather uni-typed) lambda calculus are made because they simplify a lot of operations that one could be interested (such as Booleans or the Church numerals themselves).
As an example the function abs could be "implemented" by just applying the identity function to such an extended numeral which will get rid of one lambda abstraction (and in case of a negative number, keep the absolute value as is).
If you're interested, here is an article that talks more about this definition which is worth a read.
Add++, 9 bytes
L,d0<@0>_
How it works
L, - Create a lambda.
Example argument: -8
d - Duplicate; STACK = [-8 -8]
0 - Push 0; STACK = [-8 -8 0]
< - Less than; STACK = [-8 0]
@ - Reverse; STACK = [ 0 -8]
0 - Push 0; STACK = [ 0 -8 0]
> - Greater than; STACK = [ 0 1]
_ - Subtract; STACK = [-1]
Implicitly return -1
REXX, 16 bytes
say sign(arg(1))
Implicit, 1 byte
±
After implicits, this program looks like:
$±%
$ read integer input
± push sign
% print
GolfScript, 13 bytes
~.{.abs/}{}if
How it Works
Divide by itself if 0 otherwise do nothing, and leaving a zero on the stack to be printed.
dc, 15 bytes
[_1*]sa?dd0>a/p
Explanation
This (ab)uses the fact that dc keeps the stack as is, if you're trying to divide by 0 which really helps for this challenge:
[_1*]sa # store the macro in register a (macro negates the top)
? # push input to stack
d # duplicate top
d0>a # if top is negative, execute macro
/ # divides top two values
p # print the top of the stack
LOLCODE, 191 bytes
HAI 1.3
I HAS A J ITZ A NUMBR
GIMMEH J
BIGGR OF J AN 0, O RLY?
YA RLY
VISIBLE "1"
NO WAI
BOTH SAEM "0" AN J, O RLY?
YA RLY
VISIBLE "0"
NO WAI
VISIBLE "-1"
OIC
OIC
KTHXBYE
Triangular, 26 15 bytes
$\:-|0U%<g/l0P<
Formats into this triangle:
$
\ :
- | 0
U % < g
/ l 0 P <
Old broken version that I understand:
$\:-%0U..g/l0P<
Try it online! Currently nonworking until Dennis pulls; found some interpreter bugs.
Formats into this triangle:
$
\ :
- % 0
U . . g
/ l 0 P <
How it works: The code, without directionals, is read as $:0gP0lU-%.
$reads an integer from standard input.
stack:i:duplicates the top stack value.
stack:i,i0pushes0to the stack.
stack:i,i,0gpushesi>0to the stack and discards both values used (thanks, Luis Mendo).
stack:i,i>0Ppops the top stack value into the register.
stack:i0pushes 0 to the stack.
stack:i,0lpushesi<0to the stack and discards the values used.
stack:i<0Upulls the register onto the stack.
stack:i<0,i>0-computes a postfix subtract.
stack:i<0-i>0%prints the top stack value as an integer.
Idea thanks to caird.
dc, 22 bytes
[pq]sqd0=qdd*vr1-d*v-p
I don't like that 10 bytes of this is eaten up testing for zero, will continue to mull over that. The second half, dd*vr1-d*v-p uses the square root of the square to calculate the absolute value of both our value to test and that value less one. Subtracting the latter from the former yields 1 for a positive value, -1 for a negative.
Acc!!, 50 49 bytes
N
Count i while 45/_ {
Write _
49
}
Write 48+_/49
Acc!! reads input from stdin one character code at a time. This program decides what to output simply based on the first character of the input:
- If it's
-, output-1 - If it's
0, output0 - Otherwise, output
1
Since Acc!! is a very bare-bones language, we have to use a loop for a conditional and integer division for comparison.
Commented version
# Read a character code from input and store it in _ (the accumulator)
N
# If that character was a minus sign (ASCII 45), 45/_ will be 1 and this loop will run
# If that code was a digit (ASCII 48-57), 45/_ will be 0 and the loop will be skipped
Count i while 45/_ {
# For negative numbers, output the minus sign
Write _
# Set the accumulator to ASCII code of 1 so we will break out of the loop and write a 1
49
}
# If the input was 0 (ASCII 48), _/49 will be 0 and the next line will write a 0
# Otherwise, _/49 will be 1 and the next line will write a 1
Write 48+_/49
T-SQL, 36 bytes
CREATE PROC s @ INT AS PRINT SIGN(@)
Usage:
EXECUTE s -5464
Haskell, 23 characters
A true approach, not using built-ins but function composition (the dot):
(1-).fromEnum.compare 0
(or with more space)
(1-) . fromEnum . compare 0
Explanation:
compare 0 : partially applying the compare function to
the first argument 0 results in a function which takes
a number and compares it to 0.
(compare 0) n = compare 0 n =
LT : if 0 < n
EQ : if 0 = n
GT : if 0 > n
fromEnum : it maps LT to 0, EQ to 1 and GT to 2
(1-) : n -> 1 - n
Plain English 101 81 bytes
To put a n number's sign into a s number:
Get the sign of the n returning the s.
Ungolfed version:
To put a number's sign into another number:
Get the sign of the number returning the other number.
Either version can be used to golf the client code -- and make the client code more readable. For example, the following line of code displays a Windows message box containing the number -1 in the message body:
Debug -456's sign.
The Plain English IDE is available at github.com/Folds/english. The IDE runs on Windows. It compiles to 32-bit x86 code.
Excel VBA, 10 Bytes
Anonymous VBE immediate window function that takes input from cell [A1] and outputs -1,0 or 1 to the VBE immediate window
?Sgn([A1])
Python 3, 20 bytes
Since Python 3 doesn't have access to cmp like Python 2 does, it's a little longer
lambda n:(n>0)-(n<0)
Fourier, 18 17 bytes
I~A<0{1}{`-`}A/Ao
Explanation pseudocode:
A = Input
If A<0 Then
Print "-"
End If
Print A/A
tcl 24 23
puts [expr $n<0?-1:$n>0]
Thanks to http://wiki.tcl.tk/819 page authors!
UPDATE: based on the C answer https://codegolf.stackexchange.com/a/103831/29325
puts [expr !!$n|$n>>31]
can be run on http://rextester.com/live/BKGZ8868 where i tested with -9,0,9
C (GCC), 24 23 22 18 bytes
Thanks to @aross and @Steadybox for saving a byte!
f(n){n=!!n|n>>31;}
Not guaranteed to work on all systems or compilers, works on TIO.
C, 24 20 19 18 bytes
I abuse two C exploits to golf this down; This is in C (GCC).
f(a){a=a>0?:-!!a;}
Revision History:
1) f(a){return(a>0)-(a<0);} //24 bytes
2) f(a){a=(a>0)-(a<0);} //20 bytes
3) f(a){a=a>0?:-1+!a;} //19 bytes
4) f(a){a=a>0?:-!!a;} //18 bytes
Revision 1: First attempt. Simple logic
Revision 2: Abuses a memory/stack bug in GCC where, as far as I can tell, a non-returning function will return the last set variable in certain cases.
Revision 3: Abuses ternary behavior where undefined result will return conditional result (which is why the true return on my ternary is nil)
Revision 4: Subtract a bool cast (!!) from the ternary conditional substitution for nil referenced in revision 2.
Brain-Flak 74 42 40 Bytes
Saved 2 bytes thanks to 1000000000
{([({}<([()])>)]<>(())){({}())<>}}{}({})
Explanation:
{ } # if 0 do nothing
( ) # push:
{}< > # the input, after
( ) # pushing:
[ ] # negative:
() # 1
( ) # Then push:
[ ] # the negative of the input
<> # on the other stack with:
() # a 1
( ) # pushed under it
{ } # while 1:
({}()) # increment this stack and...
<> # switch stacks
{} # pop the top (the counter or 0 from input)
( ) # push:
{} # the top (this is a no-op, or pushes a 0)
APL (Dyalog APL), 1 byte
Works for complex numbers too, returning 1∠θ:
×
Without that built-in, for integers (as per OP):
¯1⌈1⌊⊢
¯1⌈ the largest of negative one and
1⌊ the smallest of one and
⊢ the argument
... and a general one:
>∘0-<∘0
>∘0 more-than-zero
- minus
<∘0 less-than-zero
Scala, 16 bytes
n=>n compareTo 0
Java 8, 33, 17, 14 bytes
i->i>0?1:i>>31
Does not rely on any questionable code constructs or fragments. This is a complete functional interface implementation.
Ruby, 19 bytes
Not quite as golfy as my other answer.
->n{("%+b"%n)[0,2]}
Outputs -1, +0, +1
Symbolic Python, 24 bytes
Like many other solutions, this uses the formula s(x) = (x > 0) - (x < 0). Note that this solution is non-competing as the language postdates the challenge.
__={}>{}
_=(_>__)-(_<__)
Symbolic Python is a restricted source version of Python: all alphanumeric characters are banned.
The interpreter automatically puts input in the variable _. From there, the code works like so:
{}>{}generates the valueFalse. This is then assigned to the variable__. Although it's technically a boolean, we use this as the integer 0:(_>__)checks whether the input is greater than 0.(_<__)checks whether the input is smaller than 0. These booleans are then interpreted as integers, and the first is subtracted from the second.- The result of this is put in the variable
_, which is automatically printed after execution.
Befunge-93, 23 21 20 bytes
Thanks to @Mistah Figgins for saving me two three bytes
I'm sure this is further golfable. I'll look at it again in the morning.
&:#@!#._0`#@:#._1-.@
Only takes in one line of input for each run, but that's within spec, I guess.
MATLAB + Octave, 15bytes
There are a few other Octave/MATLAB answers, but two of the others are simply using a built in, and the other is significantly longer.
The anonymous function:
@(a)(a>0)-(a<0)
Quite simple. If a>0, the answer will be (1-0)=1. If a<0, the answer will be (0-1)=-1. If a==0 the answer will be (0-0)=0.
You can try online here. Simply run the above code and then try with ans(input).
Pushy, 7 bytes
This is probably the strangest-looking program I've ever written...
&?&|/;#
It uses sign(x) = abs(x) / x, but with an explicit sign(0) = 0 to avoid zero division error.
\ Take implicit input
&? ; \ If the input is True (not 0):
&| \ Push its absolute value
/ \ Divide
# \ Output TOS (the sign)
This works because x / abs(x) is 1 when x is positive and -1 when x is negative. If the input is 0, the program jumps to the output command.
4 bytes (non-competing)
Because of holidays and having too much time, I've done a complete rewrite of the Pushy interpreter. The above program still works, but because 0 / 0 now default to 0, the following is shorter:
&|/#
Excel, 8 bytes
=Sign(n)
Pretty basic, but the only language I feel complete confidence in.
Without a builtin!
Excel, 23 bytes
=If(n>0,1,If(n<0,-1,0))
not so confident
Crystal Reports Formula (Noncompete), 24 bytes
IIF(n>0,1,IIF(n<0,-1,0))
MS Excel, 9 Bytes
Takes Input from cell A1.
=SIGN(A1)
Piet, 188 53 46 41 bytes
5bpjhbttttfttatraaearfjearoaearbcatsdcclq
Online interpreter available here.
This piet code does the standard (n>0)-(n<0), as there is no sign checking builtin. In fact, there is no less-than builtin, so a more accurate description of this method would be (n>0)-(0>n).
The text above represents the image. You can generate the image by pasting it into the text box on the interpreter page. For convenience I have provided the image below where the codel size is 31 pixels. The grid is there for readability and is not a part of the program. Also note that this program does not cross any white codels; follow the colored codels around the border of the image to follow the program flow.
Explanation
Instruction Δ Hue Δ Lightness Stack
------------ ----- ----------- --------------------
In (Number) 4 2 n
Duplicate 4 0 n, n
Push [1] 0 1 1, n, n
Duplicate 4 0 1, 1, in, in
Subtract 1 1 0, in, in
Duplicate 4 0 0, 0, in, in
Push [4] 0 1 4, 0, 0, in, in
Push [1] 0 1 1, 4, 0, 0, in, in
Roll 4 1 0, in, in, 0
Greater 3 0 greater, in, 0
Push [3] 0 1 3, greater, in, 0
Push [1] 0 1 1, 3, greater, in, 0
Roll 4 1 in, 0, greater
Greater 3 0 less, greater
Subtract 1 1 sign
Out (Number) 5 1 [Empty]
[Exit] [N/A] [N/A] [Empty]
To reduce the filesize any further, I would need to actually change the program (gasp) instead of just compressing the file as I have been doing. I would like to remove one row which would golf this down to 36. I may also develop my own interpreter which would have a much smaller input format, as actually changing the code to make it smaller is not what code golf is about.
The mods told me that the overall filesize is what counts for Piet code. As the interpreter accepts text as valid input and raw text has a much smaller byte count than any image, text is the obvious choice. I apologize for being cheeky about this but I do not make the rules. The meta discussion about this makes my opinions on the matter clear.
If you think that that goes against the spirit of Piet or would like to discuss this further for any reason, please check out the discussion on meta.
C#, 40 bytes
b=>System.Console.Write(b>0?1:b<0?-1:0);
Or with a built-in:
C#, 44 bytes
using System;b=>Console.Write(Math.Sign(b));
Unfortunately it's longer, then the first solution.
C, 23 bytes
A more portable (I think) 23-byte solution in C:
f(n){return(n|1)%2-!n;}
///, 52 36 bytes
/a/\/1\/\///2a3a4a5a6a7a8a9a10a11/1/
Ungolfed, explanation:
/2/1/
/3/1/
/4/1/
/5/1/
/6/1/
/7/1/
/8/1/
/9/1/
/10/1/
/11/1/
It's basically a MapReduce implemenatation, i.e. there are two phases:
- Replace all occurrences of digits
2-9by1, e.g.1230405->1110101 - Reduce pairs of
11or10to1repeatedly, e.g.1110101->1
If there was a - in front initially, it will remain and the output will be -1. A single 0 is never replaced, thus resulting in itself.
Update: Save additional 16 bytes by aliasing //1/ with a, thanks to Martin Ender.
Factor, 71 bytes
Expects a string.
[ 0 swap nth { { CHAR: - [ -1 ] } { CHAR: 0 [ 0 ] } [ drop 1 ] } case ]
ungolfed:
: sign-of ( x -- y ) 0 swap nth
{
{ CHAR: - [ -1 ] }
{ CHAR: 0 [ 0 ] }
[ drop 1 ]
} case ;
GNU Sed, 19 bytes (20 counting the r flag)
/^0+$/b;s/[0-9]+/1/
(Using the -r flag)
Translation:
/^0+$/b;
If the number is zero, skip to the end of the script
s/[0-9]+/1/
Substitute any other numbers with 1. If it's negative the negative sign will remain too.
Python 3, 13 bytes
n//abs(n-.1)
Hexagony, 13 bytes
?</!~/~@$\!@
Expanded:
? < /
! ~ /
~ @ $ \ !
@ . . .
. . .
Hexagony truthy/falsiness for numbers checks based on being positive or not. This makes singling out zero a bit tricky, so we check if a number and its negation are both non-positive to check for zero. Uses the unprintable character 0x01 to literally store 1 in a memory edge to save a byte zeroing the edge first. In the expanded version it is between the ~ and the / on the second line.
Breakdown:
For positive numbers the code is very simple. We start at the top left moving eastward, then take the fork to the right. The rest of the program is "linear" along the surface of the code, giving: ?<0x01\.!@ where both \ and . are no-ops. 0x01 sets the current memory edge to 1 and then ! prints that and @ ends the program.
For negative numbers and zero, we start the same but turn left at the <. This leads us back around to the \ but this time approaching from the southwest. This time it acts as a mirror and redirects the instruction pointer westward. The $ allows us to skip the program-ending @. Next we hit ~ which negates the value that we read in. If the number was negative it is now positive, and if it was zero it is still not positive.
When hitting the edge of the hexagon we wrap to the right if the value was positive and to the left if the value was negative or zero. Negative numbers will then wrap to the right and begin moving westwards from the top right. Hitting some mirrors leads us to a familiar looking path starting with the edge being set to 1. Then ~ negates it and ! prints giving -1. We wrap around and hit the other @.
Zero will instead wrap to the bottom, which has nothing but no-ops. Then it wraps back to the middle and is printed by !. Then some mirrors redirect us to the @ to end the program.
Python 2, 26 Bytes
b=input()
print(b>0)-(b<0)
Brain-Flak, 48 46 40 bytes
{([({}<([()])>)]<>(())){({}())<>}}{}({})
Explanation
{ }{}({}) #Do nothing if zero
({}<([()])>) #Put a -1 under input
([ ]<>(())) #Put 1 and a negative copy of input on the off stack
{ } #Until zero
({}()) #Increment
<> #Swap
Math++, 28 bytes
?>a
3+2*!a>$
a/sqrta*a
0>$
0
JavaScript (ES6), 9 bytes
Math.sign
Straightforward.
The shortest non-builtin is 13 bytes:
n=>n>0|-(n<0)
Thanks to @Neil, this can be golfed by a byte, but at the cost of only working on 32-bit integers:
n=>n>0|n>>31
Or you could do
n=>n>0?1:!n-1
which seems more golfable, but I'm not sure how.
Turing Machine code, 65 bytes
0 0 0 * halt
0 - - r 2
0 * 1 r 3
2 * 1 r 3
3 * _ r 3
3 _ _ * halt
JavaScript (ES6), 14 bytes
No conditionals, no Math lib usage
x=>(x>0)-(x<0)
Explanation
x > 0 is true/false for positives/non-positives and cast to number (1/0) in case for subtraction.
x < 0 is analogous for negatives, so we end up with 1-0 for positives, 0-0 for zero and 0-1 for negatives.
GNU sed, 17 15 14 bytes
-2 bytes thanks to zeppelin. -1 byte thanks to manatwork.
/^0/!s/\w\+/1/
Actually, 1 byte
s
Another case of exactly what it says on the tin - s is the sign function.
Without the builtin (4 bytes):
;A\+
;A\ divides the absolute value of the input by the input. This results -1 for negative inputs and 1 for positive inputs. Unfortunately, due to Actually's error handling (if something goes wrong, the command is ignored), 0 as input leaves two 0s on the stack. + rectifies this by adding them (which causes an error with anything else, so it's ignored).
TI-Basic, 11 bytes
:Input A
:A>0
:Ans-A<0
Reads from variable A.
:A>0 // Reads from A, returns 0 or 1
:Ans-A<0. // Computes A<0 first, then subtracts from previous result. Implicit print.
MATL, 6 bytes
0>EGg-
Input may be a number or an array. The result is number or an array with the corresponding values.
Try it online! Or test several cases using array input.
Explanation
This avoids using the builtin sign function (ZS).
0> % Take input implicitly. Push 1 if positive, 0 otherwise
E % Multiply by 2
Gg % Push input converted to logical: 1 if nonzero, 0 otherwise
- % Subtract. Implicitly display
COW, 225 213 201 bytes
oomMOOmoOmoOmoOmoOMoOMoOmOomOomOoMoOMMMmoOMMMMOOMOomOo
mOoMOomoOmoOmoomOomOoMMMmoOmoOmoOMMMMOOOOOmoOMOoMOomOo
mOomOoMoOMMMmoOMMMMOOMOomOomOoMoOmoOmoOmoomoOmoomOomOo
mOomoomoOMOOmoOmoOmoOMOoMMMOOOmooMMMOOM
The way that this code works is that it determines the sign by alternating adding and subtracting bigger numbers, and seeing which one was the last one that worked. Given any non-zero integer, first subtract 1, then add 2, then subtract 3, etc. and you'll eventually reach 0. Keep track of your state by alternating adding and subtracting 2 to a value that starts off at 0. For example:
-5 - 1 = -6 (current state: 0 + 2 = 2)
-6 + 2 = -4 (current state: 2 - 2 = 0)
-4 - 3 = -7 (current state: 0 + 2 = 2)
-7 + 4 = -3 (current state: 2 - 2 = 0)
-3 - 5 = -8 (current state: 0 + 2 = 2)
-8 + 6 = -2 (current state: 2 - 2 = 0)
-2 - 7 = -9 (current state: 0 + 2 = 2)
-9 + 8 = -1 (current state: 2 - 2 = 0)
-1 - 9 = -10 (current state: 0 + 2 = 2)
-10 + 10 = 0 (current state: 2 - 2 = 0)
value is now at 0. state - 1 = 0 - 1 = -1
sign of original number is -1
When you're done, subtract 1 from your state and you get the sign, positive or negative. If the original number is 0, then don't bother doing any of this and just print 0.
Detailed Explanation:
oom ;Read an integer into [0]
MOO ;Loop while [0] is non-empty
moOmoOmoOmoOMoOMoOmOomOomOo ; Decrement [4] twice
MoOMMMmoOMMM ; Increment [1], then copy [1] to [2]
MOO ; Loop while [2] is non-empty
MOomOomOoMOomoOmoO ; Decrement [0] and [2]
moo ; End loop now that [2] is empty
mOomOoMMMmoOmoOmoOMMM ; Navigate to [0], and copy to [3]
MOO ; Perform the next steps only if [3] is non-zero
OOOmoOMOoMOomOomOomOoMoOMMMmoOMMM ; Clear [3], increment [4] twice, increment [1], and copy it to [2]
MOO ; Loop while [2] is non-empty
MOomOomOoMoOmoOmoO ; Decrement [2] and increment [0]
moo ; End loop now that [2] is empty
moO ; Navigate back to [3]
moo ; End the condition
mOomOomOo ; Navigate back to [0]
moo ;End loop once [0] is empty.
moO ;Navigate to [1]. If [1] is 0, then input was 0. Otherwise, [4] contains (sign of [0] + 1)
MOO ;Perform the next steps only if [1] is non-zero
moOmoOmoOMOoMMMOOO ; Navigate to [4], copy it to the register, and clear [4].
moo ;End condition
MMMOOM ;If the register contains something (which is true iff the condition ran), paste it and print it. Otherwise, no-op and print 0.
I'm still experimenting with golfing it (you will be shocked to discover that golfing in COW is rather difficult), so this may come down a few more bytes in the future.
MarioLANG, 868 bytes
;
=
[@:
=======================================================
)) <
======================================================"
@ ((((++
======= <
==========="
@ -)+)+)+((([!))+((
=============#==== (<
===="
@ +)-[!)))
======#== ) <
========"
>([!)
"==# )) <
@ -(-)[!+ ==========="
=======#: >(([!!
"===##
@ +((-))[!-
=========#:
Ungolfed, with comments
;[>
== output zero
[@ : * start
================================================================================================== memory: [limit|limit_copy|counter_add|counter_sub|arg]
move pointer back to arg )) <
=================================================================================="===
increase counter limit
@ ((((++
================= set counters
<
============" increase counter_add by one
@ -)+)+)+ ((([! ))+((
==============#======
reset limit
(<
======="
@ +)- [! )))
=========#==== try subtraction
) <
==========="
> ( [! )
"====#==
@ -(-) [! try addition
========# )) <
==============="
> (( [! !
"=====#==#
@ +((-)) [!
===========#
output one output minus one
+: -:
=== ===
What's going on?
The program maintains 5 memory fields (right to left):
- Input value, continuously edited in search of zero
- Counter for search in negative direction (subtraction)
- Counter for search in positive direction (addition)
- Helper to reset search radius (limit)
- Current search interval radius (limit, k)
The algorithm keeps on searching for zero in both (+ and -) directions, starting at the input value. It does k negative and k+1 positive steps on each iteration, then increases k by 2. Once zero has been found, 1 or -1 is output, depending from which side it was reached.
Detection of zero as input is a special case, handled right at the beginning.
Python 3, 23 bytes
lambda n:n and n/abs(n)
I know I can make it shorter by doing (n>0) - (n<0), but everyone else seems do be doing that so I thought I would do something different.
Stacked, 4 bytes
sign
Takes input from top of stack. Bonafide function:
$sign
Shortest non-builtin so far:
:0>\0<-
Which does:
:0>\0<- stack: [..., n]
: duplicate TOS stack: [..., n, n]
0 push 0 stack: [..., n, n, 0]
> pop n,0 and push n>0 stack: [..., n, n>0]
\ switch top two stack: [..., n>0, n]
0 push 0 stack: [..., n>0, n, 0]
< pop n,0 and push n<0 stack: [..., n>0, n<0]
- subtract top two stack: [..., (n>0)-(n<0)]
Surround with [] to be a function.
awk, 17 bytes
!$0||$0=$0<0?-1:1
Test it:
$ echo 0 | awk '!$0||$0=$0<0?-1:1'
0
$ echo 2 | awk '!$0||$0=$0<0?-1:1'
1
$ echo -2 | awk '!$0||$0=$0<0?-1:1'
-1
brainfuck, 23 bytes
-<,
[
[
>-[-<]
>
]
->[>+>]
]
<.
This takes a single byte from stdin and interprets it as a signed char, printing \xff for negative, \x00 for zero, and \x01 for positive.
Viewed as an unsigned char, we are checking whether it is greater than 127, with 0 as a special case. We can do the comparison by decrementing from 255 twice at a time.
OCaml, 4 bytes
sign
Didn't even know there was a built-in for this. Alternative 18 bytes solution:
fun x->compare x 0
Go, 49 bytes
func s(x int)int{return(x>>63)|int(uint(-x)>>63)}
Note: this won't work on the playground until Go 1.8 is released due to this bug: https://github.com/golang/go/issues/16203
Javascript, 37 bytes
function s(n){return n>0?1:n<0?-1:0}
F#, 31 9 bytes
Math.Sign
(Saved 22 bytes thanks to @pmbanka's advice :))
fun(i:int)->System.Math.Sign(i)
I was about to post a C# solution.. but it already exists :(
So I decided to have some fun with F#!!
//a solution with 24 bytes, but you have to put `open System` into the file.
//Not sure if that would be valid...
fun(i:int)->Math.Sign(i)
QBIC, 18 8 bytes
:?sgn(a)
This utilizes Qbasic's SGN() function. : gets the input in variable a, ? prints.
Original version, before I learnt that QBasic has a SGN() function:
:~a=b|?a\?a/abs(a)
18 bytes. Explanation
: Get 'a' from the command line
~a=b If a == b (and b==0 by default)
|?a Then print a
\?a/abs(a) Else, print a / abs(a) --> -2/2 leaves the req. -1, 4/4 = 1
Java 1.8, 11 bytes
Math.signum
In the comments, some people pointed out that this might not technically be valid, if so, here's another version at 12 bytes:
Math::signum
C#, 16 15 bytes
Improved solution thanks to Neil
n=>n>0?1:n>>31;
Alternatively, the built-in method is 1 byte longer:
n=>Math.Sign(n);
Full program with test cases:
using System;
public class P
{
public static void Main()
{
Func<int,int> f =
n=>n>0?1:n>>31;
// test cases:
for (int i=-5; i<= 5; i++)
Console.WriteLine(i + " -> " + f(i));
}
}
BotEngine, 7x17=119
v # #0123456789
>Ie~>SSSSSSSSSSS
^ <<<<<<<<<<P
PeeS- 1e
Pe1-S0123456789
0 > SSSSSSSSS
>>>>>>>>>^
Batch, 23 bytes
@cmd/cset/a"%1>>31|!!%1
>>31 evaluates to -1 if the input is negative and 0 if it is positive, while !! evaluates to 1 if it is nonzero and 0 if it is zero, so we just have to bitwise OR the two results together.
Gema, 9 characters
Just a rewrite of Jordan's Sed solution.
0=0
<D>=1
Sample run:
bash-4.3$ gema '0=0;<D>=1' <<< $'-303\n-12\n-5\n0\n1\n20\n404'
-1
-1
-1
0
1
1
1
Gema, 19 characters
*=@cmpn{*;0;-1;0;1}
Posted just because Gema has a nice function for this task:
@cmpn{number;number;less-value;equal-value;greater-value}
Compare numbers.
Sample run:
bash-4.3$ gema '*=@cmpn{*;0;-1;0;1}' <<< -303
-1
bash-4.3$ gema '*=@cmpn{*;0;-1;0;1}' <<< 0
0
bash-4.3$ gema '*=@cmpn{*;0;-1;0;1}' <<< 404
1
Python 2, 57 bytes but no conditionals or comparitors
Just to be different, here's a solution that avoids all those ugly arithmetic functions:
def s(n):
try:r=len([1][:n])*2-n/n
except:r=0
return r
Slicing a non-empty sequence [1][:n] returns [1] when n is positive and [] when negative or zero, so to distinguish these cases, n/n throws a divide by zero error for n=0.
Clojure, 24 bytes
#(cond(> % 0)1(< % 0)-1 0 0)
An anonymous function that checks for being greater than 0, less than 0, then defaults on 0 if neither is true. cond acts as (and is a macro resulting in) an if-else tree. Unfortunately, it requires an even number of arguments, so I had to waste 2 bytes by adding an extra number to mean true to default on.
Ungolfed:
(defn sign [n]
(cond
(> n 0) 1
(< n 0) -1
:else 0))
GameMaker Language, 22 bytes
return sign(argument0)
Alternative solutions:
return median(1,argument0,-1)
a=argument0 return (a>0)-(a<0)
a=argument0 return max(-1,min(a,1))
a=argument0 if a return a/abs(a)return 0
TI-Basic, 8 bytes
median({1,Ans,~1
Alternative solutions (feel free to suggest more):
max(~1,min(Ans,1 8 bytes
0:If Ans:Ans/abs(Ans 9 bytes
(Ans>0)-(Ans<0 10 bytes
x86_64 machine language on Linux, 13 bytes
0: 31 c0 xor %eax,%eax
2: 85 ff test %edi,%edi
4: 0f 9f c0 setg %al
7: c1 ef 1f shr $0x1f,%edi
10: 29 f8 sub %edi,%eax
12: c3 retq
The input (first function parameter) is passed into %edi. To try it out, compile and run the following C program
#include<stdio.h>
#include<stdlib.h>
#define s(x) ((int(*)(int))"\x31\xc0\x85\xff\xf\x9f\xc0\xc1\xef\x1f\x29\xf8\xc3")(x)
int main(){
printf( "%d %d %d\n", s(-5), s(0), s(44) );
}
PHP, 39 38 bytes
no comparison operators
<?=($n=$argv[1])&PHP_INT_MIN?-1:1-!$n;
should work on most systems.
PHP_INT_MIN has only one bit set: the most significant one. If this is set in the input, it is negative.
!$n (cast to integer by the subtraction) evaluates to 0 for positive values and 1 for 0.
lame solution, 30 bytes
<?=($n=$argv[1])?abs($n)/$n:0;
works also on floats.
V 14 12 bytes
Thanks @DJMcMayhem for 2 bytes. Uses a reg-ex to do the substitution. Kind of fun, because it's not a built-in. I have a more fun function, but it's not working the way I expected.
ͨ-©½0]/±1
This just translates to :%s/\v(-)=[^0].*/\11 which matches one or more - followed by anything but 0, followed by anything any number of times. It's replaced with the first match (so either a - or nothing) and a 1. The regex doesn't match 0, so that stays itself.
The More Fun Way (21 bytes)
é
Àé12|DkJòhé-òó^$/a
This accepts the input as an argument rather than in the buffer.
é<CR> Insert a new line.
À run the argument as V code. a - will move the cursor to the previous line, and any number will become the count for the next command
é1 insert (count)1's
2| move to the second column
D delete everything from the second column onwards (leaving only one character)
kJ Join the two lines together.
òhé-ò translates to: "run hé- until breaking". If the 1 was on the second line, this breaks immediately after the h. If it was on the first line, it will insert a - before breaking.
ó^$/a This fixes the fact that -1,0,1 will leave a blank, and replaces a blank with the argument register.
Forth, 22 bytes
Golfed
: S dup 0< swap 0> - ;
Test
: S dup 0< swap 0> - ; ok
0 S . 0 ok
1 S . 1 ok
-1 S . -1 ok
12345 S . 1 ok
-12345 S . -1 ok
Clojure, 23 bytes
#(condp > % 0 -1 1 0 1)
This condp macro expands to "if less than 0 return -1, if less than 1 return 0 else 1".
(macroexpand '(condp > % 0 -1 1 0 1))
(let* [pred__7749 > expr__7750 %] (if (pred__7749 0 expr__7750) -1 (if (pred__7749 1 expr__7750) 0 1)))
Vim, 22 bytes
xVp:s/-/-1^M:s/[1-9]/1^M
Saved one byte thanks to @DJMcMayhem!
Here, ^M is a literal newline.
As @nmjcman101 pointed out in the comments, a single regex can be used (:s/\v(-)=[^0].*/\11^M, 20 bytes) instead, but since this is basically the same as a Retina answer would be, I'm sticking to my own method.
Explanation:
xVp Delete everything except the first character. If the number is negative, this leaves a -, a positive leaves any number between 1 and 9, and 0 leaves 0.
:s/-/-1^M Replace a - with a -1
:s/[1-9]/1^M Replace any number between 1 and 9 with 1.
Here's a gif of it running with a negative number (old version):
Here's it running with 0:
Running with positive:
Jellyfish, 3 or 6 bytes
3 bytes with built-in:
p*i
Print (p) the sign (*) of the input (i).
Automatically threads over lists.
6 bytes without built-ins:
p%S
+i
Print (p) the division (%) of the input (i, taken from south with S) by the absolute value (+) of the input.
Conveniently, division by 0 yields 0 in Jellyfish.
This version also threads over lists.
Try it online!
SAS Macro Language, 43 bytes
In the extremely wordy language...
%macro s(n);%put(%sysfunc(sign(&n)));%mend;
Cubix, 10 bytes
(W0^I?>O2@
This code is wrapped to the following cube net:
( W
0 ^
I ? > O 2 @ . .
. . . . . . . .
. .
. .
The code is then run with the IP (instruction pointer) starting on the I, facing east. I inputs a signed integer from STDIN, pushing it onto the stack.
The next command is ?, which changes the direction of the IP depending on the sign of the top item. If the input is 0, it keeps moving in same direction, running through the following code:
>- Point the IP to the east. (No-op since we're already going east.)O- Output the top item as an integer.2- Push 2 to the stack. This is practically a no-op, because...@- Terminates the program.
If the input is negative, the IP turns left at the ?; because this is a cube, the IP moves onto the 0 in the second row, heading east. 0 pushes a literal 0, then this code is run:
^- Point the IP north.W- "Sidestep" the IP one spot to the left.(- Decrement the top item.
The TOS is now -1, and the IP wraps around the cube through a bunch of no-ops . until it hits the >. This runs the same output code mentioned above, outputting -1.
If the input is positive, the same thing happens as with negative inputs, with one exception: the IP turns right instead of left at the ?, and wraps around the cube to the 2, which pushes a literal 2. This is then decremented to 1 and sent to output.
Javascript, 18 bytes
x=>x/Math.abs(x)|0
x/Math.abs(x) is always 1 if x is positive and -1 if x is negative. If x is 0, it returns Nan, which we transform to 0 with the |0 bit.
PARI/GP, 4 bytes
sign
Another boring built-in.
PHP, 16 bytes
Uses the new spaceship operator.
<?=$argv[1]<=>0;
Loader, 61+44+1=106 bytes
Main module, 61 bytes
readline 0
set B =48
load a
set B =45
set K -1
load a
print 1
Module a, 44 bytes
decr B
decr *0
B:load a
~*0:print K
~*0:exit
Befunge, 11 bytes
&:0`\0\`-.@
This is just the obvious (N > 0) - (0 < N) calculation.
& Read N from stdin.
: Make a duplicate copy.
0` Calculate N > 0.
\ Swap the second copy to the top of the stack.
0\` Calculate 0 > N.
- Subtract the two comparisons: (N > 0) - (0 < N)
.@ Output the result and exit.
As Martin Ender pointed out, there's potentially a 2-byte shorter solution, using the same idea as his ><> answer:
1~"/"-%.@
Unfortunately this only works if the result of a modulo operation takes the sign of the divisor, which is not that common in Befunge implementations (in particular the reference interpreter doesn't work this way).
1 Push 1 onto the stack for later use.
~ Read a character of input (this will be '-' or an ASCII digit).
"/"- Subtract 47.
% Take the modulo of the 1 we pushed earlier with this difference.
.@ Output the result and exit.
If you want to try this out you'll probably need to use one of the Python-based interpreters like PyFunge or Befungee. I suspect Fungi might work too.
Wonder, 4 bytes
sign
Usage:
sign 1
Builtin.
Bonus solution (no builtin), 7 bytes
tt cmp0
Usage:
(tt cmp0)5
Uses a compare function with 0.
Stack Cats, 6 + 4 = 10 bytes
_[:I!:
+4 bytes for the -nm flags. n is for numeric I/O, and since Stack Cats requires programs to be palindromic, m implicitly mirrors the source code to give the original source
_[:I!:!I:]_
Try it online! As with basically all good Stack Cats golfs, this was found by brute force, beat any manual attempts by a long shot, and can't easily be incorporated into a larger program.
Add a D flag if you'd like to see a step-by-step program trace, i.e. run with -nmD and check STDERR/debug.
Stack Cats uses a tape of stacks which are implicitly filled with zeroes at the bottom. At the start of the program, all input is pushed onto the input stack, with a -1 at the base to separate the input from the implicit zeroes. At the end of the program, the current stack is output, except a base -1 if present.
The relevant commands here are:
_ Perform subtraction [... y x] -> [... y y-x], where x is top of stack
[ Move left one stack, taking top of stack with you
] Move right one stack, taking top of stack with you
: Swap top two of stack
I Perform [ if top is negative, ] if positive or don't move if zero. Then
negate the top of stack.
! Bitwise negate top of stack (n -> -n-1)
Note that all of these commands are invertible, with its inverse being the mirror of the command. This is the premise of Stack Cats — all nontrivial terminating programs are of odd length, since even length programs self-cancel.
We start with
v
n
-1
... 0 0 0 0 0 ...
_ subtracts, making the top -1-n, and [ moves the result left one stack:
v
-1-n -1
... 0 0 0 0 0 ...
: swaps top two and I does nothing, since the top of stack is now zero. ! then bitwise negates the top zero into a -1 and : swaps the top two back. ! then bitwise negates the top, turning -1-n back into n again:
v
n
-1 -1
... 0 0 0 0 0 ...
Now we branch based on I, which is applied to our original n:
If
nis negative, we move left one stack and end with-non an implicit zero.:swaps, putting a zero on top, and]moves the zero on top of the-1we just moved off._then subtracts, leaving the final stack like[-1 -1], and only one-1is output since the base-1is ignored.If
nis zero, we don't move and:swaps, putting-1on top.]then moves this left-1on top of the right-1, and_subtracts, leaving the final stack like[-1 0], outputting the zero and ignoring the base-1.If
nis positive, we move right one stack and end with-non a-1.:swaps, putting the-1on top, and]moves this-1right, on top of an implicit zero._then subtracts, giving0 - (-1) = 1and leaving the final stack like[1], which is output.
Mathematica, 4 bytes
Clip
How about not using the built-in Sign and still scoring 4 bytes? ;)
Clip with a single argument clips (or clamps) the input value between -1 and 1. Since the inputs will only be integers, this is the same as using Sign.
Mathematica, 28 bytes
Limit[2ArcTan@x#/Pi,x->∞]&
Mathematica, 30 bytes
2HeavisideTheta@#-1/._[_]->1/2&
Mathematica, 76 bytes
Round@Integrate[E^(2#+I t#)/(2+I t)/Pi,{t,-∞,∞},PrincipalValue->True]-1&
Just to be different :)
Octave, 26 24 bytes
f=@(x)real(asin(x))/pi*2
This is my first code-golf Octave answer, any golfing tips are appreciated!
The idea for taking the asin comes from the question where it says output the sign :)
Explanation
Note: dividing the number by pi and multiplying it by 2 is the equivalent of dividing the entire number by pi/2
Case 0:
asin(0) yields 0. Taking the real part of it and dividing it by pi/2 makes no difference to the output.
Case positive:
asin(1) yields pi/2. asin of any number bigger than 1 will give pi/2 + complex number. Taking the real part of it gives pi/2 and dividing it by pi/2 gives 1
Case negative:
asin(-1) yields -pi/2. asin of any number smaller than -1 will give -pi/2 + complex number. Taking the real part of it gives -pi/2 and dividing it by pi/2 gives -1
WolframAlpha, 3 bytes
Try it online: sgn
><>, 9 8 bytes
Thanks to Sp3000 for saving a byte.
'i$-%n/
There's an unprintable 0x01 before the /.
Explanation
This is a port of my character code-based Labyrinth answer.
' Push the entire program (except ' itself) onto the stack, which ends
with [... 1 47].
i Read the first character of the input.
$- Subtract the 47.
% Take the 1 modulo this value.
n Output the result as an integer.
0x01 Unknown command, terminates the program.
R, 25 bytes
'if'(x<-scan(),x/abs(x),0)
Takes the number to STDIN. Then checks if it's zero, if not, returns x/|x| which is either 1 of -1, and outputs 0 if x=0.
This is without using the builtin sign of course.
Octave, 4 bytes
As with many others, a built-in:
sign
Please, read the first sentence of this meta post before voting.
Labyrinth, 8 bytes
1,_47-%!
I'm posting this as a separate answer because my other Labyrinth answer is based on arithmetic on the actual numerical input value, whereas this mostly ignores the number and works with the character code of the first character instead.
Explanation
So yeah, this reads the first character code which is either 45 (-, which should yield -1), 48 (0, which should yield 0) or 49 to 57 (1-9, which should yield 1). This mapping can be accomplished via the simple formula 1 % (x - 47). To see why this works, here is the breakdown of the code for 3 different examples:
Code Comment Example -5 Example 0 Example 5
1 Push 1. [1] [1] [1]
, Read character. [1 45] [1 48] [1 53]
_47- Subtract 47. [1 -2] [1 1] [1 6]
% Modulo. [-1] [0] [1]
! Print. [] [] []
The instruction pointer then hits a dead end, turns around and terminates when % now attempts a division by zero.
Another simple computation that works:
x -= 46
x %= x-1
Perl, 9 bytes
Requires -E at no extra cost.
say<><=>0
Usage
perl -E 'say<><=>0' <<< -9999
-1
perl -E 'say<><=>0' <<< 9999
1
perl -E 'say<><=>0' <<< -0
0
I'm happy with the fish operator!
Retina, 9 bytes
[1-9].*
1
Replaces a non-zero digit and everything after it with 1. This leaves a potential leading - intact and changes all numbers except 0 itself to absolute value 1.
Labyrinth, 10 bytes
?:+:)%:(%!
Explanation
Labyrinth's control flow semantics actually give you a "free" way to determine a number's sign, because the chosen path at a 3-way fork depends on whether the sign is negative, zero or positive. However, I haven't been able to fit a program with junctions into less than 12 bytes so far (although it may be possible).
Instead, here's a closed-form solution, that doesn't require any branches:
Code Comment Example -5 Example 0 Example 5
? Read input. [-5] [0] [5]
:+ Double. [-10] [0] [10]
:) Copy, increment. [-10 -9] [0 1] [10 11]
% Modulo. [-1] [0] [10]
:( Copy, decrement. [-1 -2] [0 -1] [10 9]
% Modulo. [-1] [0] [1]
! Print. [] [] []
The instruction pointer then hits a dead end, turns around and terminates when % now attempts a division by zero.
Doubling the input is necessary to make this work with inputs 1 and -1, otherwise one of the two modulo operations would already attempt a division by zero.
Perl 6, 9 bytes
+(*cmp 0)
Explanation:
+( # turn into a number
* # Whatever (input)
cmp # compared to
0 # 0
)
Mathematica, 4 bytes
Sign
Exactly what it says on the tin
Haskell, 6 bytes
signum
Just a boring built-in.
Jelly, 1 byte
Ṡ
The monadic sign atom, Ṡ, does exactly what is specified for an integer input, either as a full program or as a monadic link (function taking one argument).
Japt, 2 bytes
Ug
U is the input number, and g is the sign function on numbers. Output is implicit.
Ruby, 10 bytes
->x{x<=>0}
Clojure, 14 bytes
#(compare % 0)
This uses the built-in compare function of clojure: it returns a 1 if the first arg is greater than the second arg, 0 if it's equal, and -1 if it's smaller.
Usage:
(#(...) {number})







