84
\$\begingroup\$

Given a number N, output the sign of N:

  • If N is positive, output 1
  • If N is negative, output -1
  • If N is 0, output 0

N will be an integer within the representable range of integers in your chosen language.

The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](https://esolangs.org/wiki/Fish), 121 bytes

/* Configuration */

var QUESTION_ID = 103822; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();
    
    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
12
  • 52
    \$\begingroup\$ This is a trivial challenge with a lot of trivial solutions. There are however some non-trivial solutions too. To voters: Please read the first sentence of this meta post before upvoting builtin functions. \$\endgroup\$ Commented Dec 20, 2016 at 10:10
  • 9
    \$\begingroup\$ This could probably use a leaderboard. \$\endgroup\$ Commented Dec 20, 2016 at 11:13
  • 3
    \$\begingroup\$ @MrLister upvote how you want, but really you should look for creativity instead of code length. \$\endgroup\$
    – FlipTack
    Commented Dec 28, 2016 at 20:13
  • 3
    \$\begingroup\$ @FlipTack Oh, I thought it was codegolf. \$\endgroup\$
    – Mr Lister
    Commented Dec 28, 2016 at 20:23
  • 4
    \$\begingroup\$ @MrLister that's the objective winning criterion. but does it really take more effort to type s for a sign builtin, or use some clever bitshifting/maths to work it out? Have a look at this meta post \$\endgroup\$
    – FlipTack
    Commented Dec 28, 2016 at 20:25

194 Answers 194

1 2
3
4 5
7
3
\$\begingroup\$

Alice, 19 13 12 bytes

-6 bytes thanks to Martin Ender -1 byte thanks to Julian

1i'/-%/ o @

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ It's normally not necessary to use " to push numbers onto the stack. A simpler way is to push the 4 in Cardinal mode and then append the 7 in Ordinal mode. You can then also save a few bytes by interleaving the two segments in Ordinal mode: tio.run/##S8zJTE79/98w00Q/n0tXVSHG3EH//39dQyNjAA (I also push the 1 at the start to avoid the ~ but it doesn't really make a difference for the byte count) \$\endgroup\$ Commented Jun 4, 2021 at 13:15
  • \$\begingroup\$ Ah, I somehow didn't see appending numbers in Ordinal while checking the command list. Thanks for the advice! \$\endgroup\$ Commented Jun 4, 2021 at 13:25
  • \$\begingroup\$ Down to 12 bytes using '/ to get the value 47 on the stack Try it online! \$\endgroup\$
    – Julian
    Commented Mar 23, 2023 at 0:28
3
\$\begingroup\$

Lua, 46 45 38 33 32 26 bytes

load"return-1+2/(0^...+1)"

Try it online!

-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 n is negative, 0^n+1 yields the value inf, which then becomes zero when 2 is divided by it. Subtract 1 and this is -1.
  • If n is zero, 0^n+1 yields 2, becoming 1 when 2 is divided by it. Subtract 1 and this is 0.
  • If n is positive, 0^n+1 is 1, becoming 2 when 2 is divided by it. Subtract 1 and this is 1.

Other languages identified so far in which this works:


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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can also create a function using load and ... for 26 bytes \$\endgroup\$
    – Jo King
    Commented Mar 23, 2023 at 0:54
3
\$\begingroup\$

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>

\$\endgroup\$
2
\$\begingroup\$

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})
\$\endgroup\$
0
2
\$\begingroup\$

Haskell, 6 bytes

signum

Just a boring built-in.

\$\endgroup\$
2
\$\begingroup\$

Perl 6, 9 bytes

+(*cmp 0)

Try it online!

Explanation:

+(     # turn into a number

  *    # Whatever (input)
  cmp  # compared to
  0    # 0

)
\$\endgroup\$
2
\$\begingroup\$

CJam, 1 byte

g

Try it online!

Another built-in, just for the sake of completeness.

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Median@{#,1,-1} and #~Min~1~Max~-1 if you want some more ideas ;) \$\endgroup\$ Commented Dec 20, 2016 at 12:09
  • \$\begingroup\$ Personal challenge to you: find an implementation that's longer than 76 bytes, but fully golfed for its algorithm (can you be turned to the dark side?!). \$\endgroup\$ Commented Dec 20, 2016 at 18:43
  • \$\begingroup\$ Can I take you up on this challenge? \$\endgroup\$ Commented Dec 20, 2016 at 23:29
  • \$\begingroup\$ Of course! .. :) \$\endgroup\$ Commented Dec 21, 2016 at 0:13
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
9
  • \$\begingroup\$ This is not a full program neither an (anonymous) function, but rather just a code excerpt, which can not be reused directly, so I guess this does not qualify. \$\endgroup\$
    – zeppelin
    Commented Dec 20, 2016 at 21:29
  • 3
    \$\begingroup\$ It is technically a function, just referencing an already existing one, you can call it the same way as an anonymous function, but I don't know if such solutions are/should be allowed. \$\endgroup\$
    – user344
    Commented Dec 20, 2016 at 22:15
  • \$\begingroup\$ @zeppelin From everything I've seen, this is as acceptable as a loose anonymous function. \$\endgroup\$ Commented Dec 20, 2016 at 22:22
  • \$\begingroup\$ It would be acceptable in a language like Javascript, where evaluating the expression like "Math.sign" will evaluate to a function reference, which you can then invoke or assign to a variable. But (AFAIK) 'Math.signum' does not make a valid standalone expression in Java. Probably you can replace it with a "method reference" (i.e. Math::signum) which will produce a Function<>, which can then be assigned to a variable and invoked, to make it qualify. \$\endgroup\$
    – zeppelin
    Commented Dec 21, 2016 at 9:17
  • 1
    \$\begingroup\$ None of the solutions seem valid to me. The first for the reasons mentioned above. The second because the output is not 1, -1 or 0 but 1.0, -1.0 or 0.0. \$\endgroup\$ Commented Dec 24, 2016 at 0:15
2
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ A 17-byte alternative, but only works on GNU AWK (gawk): !$0||sub(/\w+/,1) \$\endgroup\$ Commented May 7, 2021 at 18:38
2
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ Welcome to Programming Puzzles & Code Golf! If you replace / with //, you don't need to cast to int. \$\endgroup\$
    – Dennis
    Commented Dec 22, 2016 at 3:01
  • \$\begingroup\$ Thank you! I just realised I dont even need to casting at all. I thought that if n == 0 it would evaluate to false so I would have to convert it to an int but it turns out it stays as 0. \$\endgroup\$
    – Cormac
    Commented Dec 22, 2016 at 3:15
  • \$\begingroup\$ Right, that returns a float. Nothing wrong with that, I guess. \$\endgroup\$
    – Dennis
    Commented Dec 22, 2016 at 3:18
  • \$\begingroup\$ Floats are acceptable here, since 1.0 == 1 and -1.0 == -1. Nice job using the rarely-used definition of the sign function as the derivative of the absolute value function (with f(0) = 0 explicitly defined)! \$\endgroup\$
    – user45941
    Commented Dec 23, 2016 at 14:40
2
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ That's basically a duplicate of Jordan's solution (which is 14 bytes). \$\endgroup\$
    – zeppelin
    Commented Dec 24, 2016 at 10:19
  • \$\begingroup\$ Oh. Damn. ☹ Should I remove mine then? \$\endgroup\$ Commented Dec 24, 2016 at 16:38
  • \$\begingroup\$ Well, not sure what's the current policy on this (I guess that is described somewhere on Meta), but AFAIK you can keep your answer. \$\endgroup\$
    – zeppelin
    Commented Dec 24, 2016 at 21:32
2
\$\begingroup\$

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-.@

Try it online!

Only takes in one line of input for each run, but that's within spec, I guess.

\$\endgroup\$
4
  • \$\begingroup\$ Nice First Answer! Welcome to the site. \$\endgroup\$
    – Wheat Wizard
    Commented Dec 25, 2016 at 4:54
  • \$\begingroup\$ Is there a reason for the space between the . and _ ? Seems like you could save a byte. \$\endgroup\$ Commented Jan 4, 2017 at 0:52
  • \$\begingroup\$ Also, you can move one character into the 2 "#@ #" to make "#@!#" instead of "!#@ #". Nice answer though! \$\endgroup\$ Commented Jan 4, 2017 at 5:00
  • \$\begingroup\$ You can use the same trick on :#@ # -> #@:# as well. My goal whenever writing befunge 93/98 is no whitespace at all. (he says as his own submission is 7% whitespace) \$\endgroup\$ Commented Jan 6, 2017 at 7:21
2
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can save 3 bytes by replacing pred with (1-) which allows you to replace (`compare`0) with compare 0. \$\endgroup\$
    – 0 '
    Commented Oct 20, 2017 at 7:27
2
\$\begingroup\$

Triangular, 26 15 bytes

$\:-|0U%<g/l0P<

Formats into this triangle:

     $ 
    \ : 
   - | 0 
  U % < g 
 / l 0 P < 

Try it online!


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,i
  • 0 pushes 0 to the stack.
    stack: i,i,0
  • g pushes i>0 to the stack and discards both values used (thanks, Luis Mendo).
    stack: i,i>0
  • P pops the top stack value into the register.
    stack: i
  • 0 pushes 0 to the stack.
    stack: i,0
  • l pushes i<0 to the stack and discards the values used.
    stack: i<0
  • U pulls 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.

\$\endgroup\$
1
  • \$\begingroup\$ This fails, by outputting the inverse sign. However, this is correct, and is the same length. \$\endgroup\$ Commented Oct 31, 2017 at 18:42
2
\$\begingroup\$

GolfScript, 13 bytes

~.{.abs/}{}if

Try it online!

How it Works

Divide by itself if 0 otherwise do nothing, and leaving a zero on the stack to be printed.

\$\endgroup\$
0
2
\$\begingroup\$

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.

\$\endgroup\$
0
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

Brain-Flak, 40 38 bytes

{<>(())<>{(([{}[]]))<>([{}])<>}}<>({})

Try it online!

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
\$\endgroup\$
2
\$\begingroup\$

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

Try it online!

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
\$\endgroup\$
1
  • \$\begingroup\$ Sorry, skynet got my computer before I could read the explanation. \$\endgroup\$
    – Razetime
    Commented Sep 2, 2020 at 2:26
2
\$\begingroup\$

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.

\$\endgroup\$
2
2
\$\begingroup\$

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

COW, 153 75 bytes

oomMMMmoOMoOmoOMMMMOOmoOOOOMOomOoMoOmOomOoMOOMOomoOmoOMMMOOOmooMMMmoomoOOOM

Try it online!

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.

\$\endgroup\$
2
\$\begingroup\$

Stax, 2 bytes

:+

Run and debug it

Stax has a sign builtin. Kind of boring. Here's a solution that uses clamp instead

Stax, 4 bytes

U1:c

Run and debug it

U    push -1 to stack
 1   push 1 to stack
  :c clamp input between -1 and 1
\$\endgroup\$
2
\$\begingroup\$

Java, 12 bytes

Long::signum

Try it online!

Using Long instead of Integer saves 3 bytes.

Long.signum documentation

\$\endgroup\$
2
\$\begingroup\$

BitCycle -U, 8 bytes

?v
/=
>!

Try it here!

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.
\$\endgroup\$
1 2
3
4 5
7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.