74
\$\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\$
  • 47
    \$\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\$ – Stewie Griffin Dec 20 '16 at 10:10
  • 8
    \$\begingroup\$ This could probably use a leaderboard. \$\endgroup\$ – Martin Ender Dec 20 '16 at 11:13
  • 2
    \$\begingroup\$ @MrLister upvote how you want, but really you should look for creativity instead of code length. \$\endgroup\$ – FlipTack Dec 28 '16 at 20:13
  • 3
    \$\begingroup\$ @FlipTack Oh, I thought it was codegolf. \$\endgroup\$ – Mr Lister Dec 28 '16 at 20:23
  • 3
    \$\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 Dec 28 '16 at 20:25

158 Answers 158

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
| improve this answer | |
\$\endgroup\$
  • \$\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 Dec 20 '16 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\$ – nyuszika7h Dec 20 '16 at 22:15
  • \$\begingroup\$ @zeppelin From everything I've seen, this is as acceptable as a loose anonymous function. \$\endgroup\$ – Carcigenicate Dec 20 '16 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 Dec 21 '16 at 9:17
  • \$\begingroup\$ @nyuszika7h "you can call it the same way as an anonymous function" I don't think you can, w/o changing it to Math.signum(yourArgument), which involves rewriting the program text, and that is clearly not acceptable. (and you will still have to pass an argument in somehow). \$\endgroup\$ – zeppelin Dec 21 '16 at 9:18
2
\$\begingroup\$

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.

Try it online.

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Doing I/O as decimal strings could be fun too. \$\endgroup\$ – Mitch Schwartz Dec 21 '16 at 16:48
  • \$\begingroup\$ You could argue that all numbers in BF are positive, so ,>+. is a valid answer. \$\endgroup\$ – Esolanging Fruit Dec 22 '16 at 4:38
  • 1
    \$\begingroup\$ @Challenger5 Even if that were modified to handle zero, e.g. with ,[>+>]<., I don't think that could be argued as anything other than a loophole. \$\endgroup\$ – Mitch Schwartz Dec 22 '16 at 5:49
  • \$\begingroup\$ Definitely, but it's funny. \$\endgroup\$ – Esolanging Fruit Dec 22 '16 at 5:50
  • 1
    \$\begingroup\$ @Challenger5 That would be abusing native number types to trivialize the challenge. The solution Mitch has used (interpreting the input as an 8-bit two's complement integer) is valid, and the only valid way to do this in brainfuck other than interpreting decimal strings (unless there's another way and I'm not seeing it). \$\endgroup\$ – Mego Dec 23 '16 at 14:44
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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Welcome to Programming Puzzles & Code Golf! If you replace / with //, you don't need to cast to int. \$\endgroup\$ – Dennis Dec 22 '16 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 Dec 22 '16 at 3:15
  • \$\begingroup\$ Right, that returns a float. Nothing wrong with that, I guess. \$\endgroup\$ – Dennis Dec 22 '16 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\$ – Mego Dec 23 '16 at 14:40
2
\$\begingroup\$

GNU sed, 17 15 14 bytes

-2 bytes thanks to zeppelin. -1 byte thanks to manatwork.

/^0/!s/\w\+/1/

Try it online!

| improve this answer | |
\$\endgroup\$
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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ That's basically a duplicate of Jordan's solution (which is 14 bytes). \$\endgroup\$ – zeppelin Dec 24 '16 at 10:19
  • \$\begingroup\$ Oh. Damn. ☹ Should I remove mine then? \$\endgroup\$ – Claire Cavanaugh Dec 24 '16 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 Dec 24 '16 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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Nice First Answer! Welcome to the site. \$\endgroup\$ – Wheat Wizard Dec 25 '16 at 4:54
  • \$\begingroup\$ Is there a reason for the space between the . and _ ? Seems like you could save a byte. \$\endgroup\$ – MildlyMilquetoast Jan 4 '17 at 0:52
  • \$\begingroup\$ Also, you can move one character into the 2 "#@ #" to make "#@!#" instead of "!#@ #". Nice answer though! \$\endgroup\$ – MildlyMilquetoast Jan 4 '17 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\$ – MildlyMilquetoast Jan 6 '17 at 7:21
2
\$\begingroup\$

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, output 0
  • 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
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Clever - this is the first solution I've seen that takes advantage of the fact that you only need to look at the first byte to determine the output (when using string input). \$\endgroup\$ – Mego Dec 23 '16 at 14:58
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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ This fails, by outputting the inverse sign. However, this is correct, and is the same length. \$\endgroup\$ – caird coinheringaahing Oct 31 '17 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.

| improve this answer | |
\$\endgroup\$
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.

| improve this answer | |
\$\endgroup\$
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).

| improve this answer | |
\$\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
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Japt, 2 bytes

Ug

Test it online!

U is the input number, and g is the sign function on numbers. Output is implicit.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Pyth, 2 bytes

._

herokuapp

Pyth's sign function.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Matlab, 4 bytes

sign

Matlab as well has a builtin for it.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Octave, 4 bytes

As with many others, a built-in:

sign

Please, read the first sentence of this meta post before voting.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

WolframAlpha, 3 bytes

Try it online: sgn

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Befunge, 11 bytes

&:0`\0\`-.@

Try it online!

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I think the arithmetic solution I used for my ><> answer and one of my Labyrinth answers would be 2 bytes shorter. \$\endgroup\$ – Martin Ender Dec 20 '16 at 13:46
  • \$\begingroup\$ If you use that approach you can save another byte with Befunge-98 which supports '/ for "/". (Provided any 98 interpreters exist with the correct modulo.) \$\endgroup\$ – Martin Ender Dec 20 '16 at 14:54
1
\$\begingroup\$

SAS Macro Language, 43 bytes

In the extremely wordy language...

%macro s(n);%put(%sysfunc(sign(&n)));%mend;
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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)))
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Javascript, 37 bytes

function s(n){return n>0?1:n<0?-1:0}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Sorry, updated! \$\endgroup\$ – Ostbullen Dec 21 '16 at 15:35
  • 2
    \$\begingroup\$ You could use a lambda: n=>n>0?1:n<0?-1:0 \$\endgroup\$ – Mego Dec 23 '16 at 14:45
1
\$\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
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

Try it online (commented, ungolfed version)

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python 3, 13 bytes

n//abs(n-.1)
| improve this answer | |
\$\endgroup\$
  • 7
    \$\begingroup\$ Welcome to the site, and nice first answer! Just so you know, this is only a REPL snippet, which aren't a default valid form of output. You could wrap this in a lambda to make a function submission though. lambda n:n//abs(n-.1) \$\endgroup\$ – James Dec 24 '16 at 7:27
1
\$\begingroup\$

C, 23 bytes

A more portable (I think) 23-byte solution in C:

f(n){return(n|1)%2-!n;}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.