Comparing two numbers

25

3

Challenge

Given two integers A and B as input, you must write a program which outputs if A>B, A==B or A<B.

The integers will be in any reasonable range supported by your language which includes at least 256 values.

Your program can be either a full program or a function, taking input via STDIN or function arguments.

Outputs

If A>B output

A is greater than B

If A==B output

A is equal to B

If A<B output

A is less than B

Where you replace A and B for their integer values.

Winning

The shortest program in bytes wins.

Leaderboard

var QUESTION_ID=55693,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}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="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <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><div id="language-list"> <h2>Winners 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><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>

Beta Decay

Posted 2015-08-30T22:24:24.770

Reputation: 21 478

Today on Programming Puzzles & Code Golf: ternary statements! – Trebuchette – 2015-09-01T01:29:54.170

Can functions simply return the solution instead of printing out the solution? – TheNumberOne – 2015-09-02T14:18:45.513

@TheNumberOne No, they must print the solution – Beta Decay – 2015-09-02T16:07:53.753

Answers

11

CJam, 47

q~_~-g"is
equal greater less
to than"N/Sf/f=*S*

Try it online

Explanation:

q~     read and evaluate the input (array of 2 numbers)
_      duplicate the array
~-     dump one array on the stack and subtract the numbers
g      get signum (-1 for <, 0 for ==, 1 for >)
"…"    push that string
N/     split into lines
Sf/    split each line by space
f=     get the corresponding word (for the signum) from each line
*      join the array of 2 numbers by the array of words
        it effectively inserts the words between the numbers
S*     join everything with spaces

aditsu quit because SE is EVIL

Posted 2015-08-30T22:24:24.770

Reputation: 22 326

Looks like CJam is one byte shorter than Pyth today :( – orlp – 2015-08-31T02:27:26.690

According to Defaults for reading several pieces of input, you can read the input as [A B] and eliminate the ] from your code.

– Dennis – 2015-08-31T06:13:29.933

@Dennis thanks, I had thought about it but wasn't sure. – aditsu quit because SE is EVIL – 2015-08-31T12:47:19.610

@orlp 2 bytes now, and that's a reason to smile, not to frown :) – aditsu quit because SE is EVIL – 2015-08-31T12:47:35.243

Appropriate that your code actually contains a smiley in the form of ~_~... – Darrel Hoffman – 2015-09-01T16:13:10.360

19

Python 2, 95 94 76 bytes

Input must be comma separated.

A,B=input();print A,'is',['equal to','greater than','less than'][cmp(A,B)],B

TheNumberOne

Posted 2015-08-30T22:24:24.770

Reputation: 10 855

I'm intrigued, can you explain what cmp(A,B) is and does? :) – Beta Decay – 2015-08-31T15:58:37.227

2

@BetaDecay, https://docs.python.org/2/library/functions.html#cmp. "Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.". In cPython 2.7.6, those integers' values are -1, 0, 1 respectively. The function's definition doesn't dictate this, so a pedant might insist that the exact implementation and version of python were given here rather than just "Python 2", but I expect most implementations will behave the same here.

– ymbirtt – 2015-08-31T16:48:41.073

I just want you to know that I didn't copy your answer to come up with mine. I just now saw how close they were. When I wrote mine I was having trouble running the snippet and I could've sworn there wasn't already a Python answer (must've missed the 2nd page). I wrote it completely independently, strangely enough.

– mbomb007 – 2015-09-01T15:17:00.197

@Sp3000 I checked it ,and it works perfectly fine in Python 2.7.6 – M L – 2016-01-03T03:09:36.890

1

@ML My comment was referring to a past revision but since it's now outdated I've deleted the comment

– Sp3000 – 2016-01-03T10:35:20.753

I believe you can substitute cmp(a,b) for (a>b)-(a<b) in order to translate to Python 3, but of course that's longer. See my translation attempt.

– Ogaday – 2016-02-11T13:52:52.260

10

Labyrinth, 180 152 149 bytes

<
?01.23.511.501.23};,!:?
:
= ;3.114.101.97.116.101.114.32.116.104.97.110.32.{!@
-""
; ;8.101.115:..""""""""""""^
1
.113.117.97.108.32.116.111.32.{!@

Edit: Managed to shave off 3 bytes by reusing 10 between 101, 103 and 108 (the character codes of e, g and l). The explanation below does not reflect this, but it's not a substantial change.

Explanation

There isn't much we can do in the way of saving bytes for printing the strings, that's just going to be long linear sections. So the main challenge in golfing is to avoid large amounts of unnecessary whitespace. That means we want the linear parts to "radiate out" from the left-most column. We can also gain some more savings by reusing the code that prints than B. So let's look at the control flow here:

The program starts on a grid rotation command <. This shifts the current row cyclically to the left with the IP on it, so we get this:

                                                     <
?.23.511.501.23};,!:?
:
= ;103.114.101.97.116.101.114.32.116.104.97.110.32.{!@
-""
1 ;108.101.115:..""""""""""""^
0
1.113.117.97.108.32.116.111.32.{!@

Now the IP is on an isolated cell, so it executes the same command again and again while the < travels further to the left until...

                    <
?.23.511.501.23};,!:?
:
= ;103.114.101.97.116.101.114.32.116.104.97.110.32.{!@
-""
1 ;108.101.115:..""""""""""""^
0
1.113.117.97.108.32.116.111.32.{!@

At this point, the IP has somewhere to go and executes the first linear section (the second row) from right to left. What it does is read A, copy, print. Consume the delimiting character between the numbers, print is (and spaces). Then read B, copy it and subtract A from it at the -.

At this point we hit first "fork in the road". If the difference yielded 0, the IP keeps moving straight ahead towards the bottom branch. That branch simply prints equal to and then B.

Otherwise, the IP takes a left towards the two no-ops "". Then there's another fork. If the difference was negative, the IP takes another left towards the long upper branch. That branch simply prints greater than and then B.

If the difference was positive, the IP takes a right onto the lower branch, which prints less. Now we want to reuse the than from the other branch. But at the same time we don't want to connect the two branches later on, because we'd need a whole bunch of unnecessary spaces. Instead we use a few no-ops to align the lower branch with where the than begins on the upper branch and then start manipulating the source again with ^:

                    <
?.23.511.501.23};,!:?
:                            .
= ;103.114.101.97.116.101.114 32.116.104.97.110.32.{!@
-""                          ^
1 ;108.101.115:..""""""""""""
0                            2
1.113.117.97.108.32.116.111.3 .{!@

Again, this is isolates the IP, so ^ is executed again and we get

                    <
?.23.511.501.23};,!:?        .
:
= ;103.114.101.97.116.101.114^32.116.104.97.110.32.{!@
-""
1 ;108.101.115:..""""""""""""2
0
1.113.117.97.108.32.116.111.3 .{!@

Now the IP can continue moving to the right and print than and B as required.

Martin Ender

Posted 2015-08-30T22:24:24.770

Reputation: 184 808

8

JavaScript (ES6), 66 bytes

(a,b)=>a+` is ${a<b?"less than":a>b?"greater than":"equal to"} `+b

Defines an anonymous function. Test by adding f= before it, and call it like alert(f(4, 5))


No savings to be had from the repetitive "than", unfortunately.

jrich

Posted 2015-08-30T22:24:24.770

Reputation: 3 898

Are you sure? The Java answer seems to get around the than ;) – Beta Decay – 2015-08-31T09:58:34.353

3@BetaDecay well, no. Even the Java answer would be the same length repeating the than. public void c(int a,int b){System.out.print(a+" is "+(a==b?"equal to ":a>b?"greater than ":"smaller than ")+b);} – edc65 – 2015-08-31T10:01:38.027

@BetaDecay Is this a valid answer if it doesn't actually output the text? Alternatively 7 for alert() should be added to the score. – curiousdannii – 2015-09-02T07:36:52.203

@curiousdannii Oh I see, yes this is invalid if you don't count alert() as part of your code and byte count – Beta Decay – 2015-09-02T08:54:51.890

@BetaDecay oh, I didn't realize that the answer was expected to be printed instead of just returned. If assuming a REPL environment is ok, this could be run in the FireFox console at no cost, otherwise I guess it's up to 73. – jrich – 2015-09-02T11:14:28.890

8

Java, 114 113 Bytes or 74 72 67 if we used lambda notation

Thanks to Kevin Cruijssen for currying based solution:

a->b->a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b

Old pre lambda solution

public void c(int a,int b){System.out.print(a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b);}

as user h.j.k meantion in comment, if we used lambda we can do significantly down to 74 bytes.

(a,b)->a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b;

user902383

Posted 2015-08-30T22:24:24.770

Reputation: 1 360

1Clever way of compressing than :) – TheNumberOne – 2015-08-30T23:11:40.560

4You can remove public if you want to. I would suggest making this into a lambda. You can remove the one space before the {. – TheNumberOne – 2015-08-30T23:13:55.717

1And while you're at it, add a comma after #Java so you can be on the leaderboard. ;) – TNT – 2015-08-31T00:02:34.943

1Lambda: (a, b)->a+" is "+(a==b?"equal to ":(a>b?"greater":"smaller" )+" than ")+b; (74 bytes?) – h.j.k. – 2015-08-31T09:32:05.430

A JAVA ANSWER JUST BEAT A PYTHON ANSWER! THE DAY HAS COME FRIENDS :D. (74 bytes vs 76 from the currently accepted answer).

– Anubian Noob – 2015-09-01T15:27:04.570

@AnubianNoob actually it is 72 not 74 – user902383 – 2015-09-01T16:45:14.047

2The official question spec is to say "less", not "smaller". You might as well do that and lose three bytes! I don't know Java, but will the lambda code print the text or just return it? If it doesn't print it then it's probably not a valid answer. – curiousdannii – 2015-09-02T07:44:38.807

Would this work: String c(int a,int b){return a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b;} and (a,b)->a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b; – TheNumberOne – 2015-09-02T14:24:53.990

2

@h.j.k. Shorter lambda using currying: a->b->a+" is "+(a==b?"equal to ":(a>b?"greater":"smaller" )+" than ")+b Yes, I'm aware it has been almost two years. ;) And you can indeed use less instead of smaller based on the challenge description, as mentioned by the two comments above me. Try it here to see how currying is done.

– Kevin Cruijssen – 2017-06-01T12:12:30.540

7

Julia, 69 66 bytes

f(A,B)="$A is $(A>B?"greater than":A<B?"less than":"equal to") $B"

This uses string interpolation to embed A, B, and the ternary inside a single string.

Saved 3 bytes thanks to Glen O.

Alex A.

Posted 2015-08-30T22:24:24.770

Reputation: 23 761

7

R, 80 bytes

function(A,B)cat(A,"is",c("less than","equal to","greater than")[2+sign(A-B)],B)

flodel

Posted 2015-08-30T22:24:24.770

Reputation: 2 345

1You can save 3 bytes by changing "smaller than" to "less than" to follow the spec above. +1 for not using a ternary operator. – bmarks – 2015-08-30T23:56:25.610

ah thanks, I did not catch that! fixed! – flodel – 2015-08-30T23:57:03.233

@bmarks R doesn't have a ternary operator. :P – Alex A. – 2015-08-30T23:58:41.327

@AlexA. I know. I meant that using a list and the sign function was very different from the other answers so far (most of which used ternary operators or similar). – bmarks – 2015-08-31T00:01:09.893

Right. For comparison, my first attempt using if/else was 83: function(A,B)cat(A,"is",if(A==B)"equal to"else c(if(A>B)"greater"else"less","than"),B). – flodel – 2015-08-31T00:04:17.797

7

Pyth, 52 49 bytes

jdm@cd)._-FQcj"
is
equal greater less
to than
"Qb

orlp

Posted 2015-08-30T22:24:24.770

Reputation: 37 067

6

Perl, 64 63 bytes

#!/usr/bin/perl -p
s/ /" is ".("equal to ",greaterx,lessx)[$`<=>$']/e;s/x/ than /

62 bytes + 1 byte for -p. Takes input from STDIN, with the two numbers separated by a single space:

$ echo 1 2 | ./cmp
1 is less than 2
$ echo 42 -17 | ./cmp
42 is greater than -17
$ echo 123456789 123456789 | ./cmp
123456789 is equal to 123456789

How it works:

The <=> operator returns -1, 0, or 1 depending on whether the first operand is less than, equal to, or greater than the second. Conveniently, Perl allows negative subscripts with arrays and slices, where the last element is at position -1, the second-to-last element is at position -2, and so on.

In the code

("equal to ",greaterx,lessx)[$`<=>$']

we use the return value of <=> as the subscript in a list slice to get the corresponding string, where $` is the first number and $' is the second.

To avoid repeating than, x is used as a placeholder and replaced in a second substitution at the end.


Alternative solution, 63 bytes

#!/usr/bin/perl -p
@a=(equal,greater,than,to,less);s/ / is @a[$i=$`<=>$',!$i+2] /

62 bytes + 1 byte for -p. Takes space-separated input from STDIN just like the first solution.

How it works:

This solution also uses a slice, but takes advantage of the fact that unlike list slices, array slices can be interpolated into strings (and the RHS of substitutions). This lets us drop the /e modifier and the quotes in the substitution operator.

The real trick is in the slice subscript:

@a[$i=$`<=>$',!$i+2]

For the different values of <=>, this gives:

$i  !$i+2  $a[$i]  $a[!$i+2]
----------------------------
-1    2     less      than
 0    3     equal     to
 1    2     greater   than

When an array or array slice is interpolated into a string, the elements are automatically joined by $" (by default, a single space).

ThisSuitIsBlackNot

Posted 2015-08-30T22:24:24.770

Reputation: 1 050

5

Mouse, 79 bytes

?A:?B:A.!" is "A.B.<["less than"]A.B.>["greater than"]A.B.=["equal to"]" "B.!$

When strings are encountered they're immediately written to STDOUT rather than being put on the stack. The stack can contain only integers.

Ungolfed:

? A:                            ~ Read an integer A from STDIN
? B:                            ~ Read an integer B from STDIN
A. !                            ~ Write A to STDOUT
" is "
A. B. < [ "less than" ]         ~ If A < B
A. B. > [ "greater than" ]      ~ If A > B
A. B. = [ "equal to" ]          ~ If A == B
" "
B. !                            ~ Write B to STDOUT
$                               ~ End of program

Alex A.

Posted 2015-08-30T22:24:24.770

Reputation: 23 761

4

MATLAB, 105 bytes

x=input('');y=input('');t={'less than','greater than','equal to'};
sprintf('%i is %s %i',x,t{(x>=y)+(x==y)+1},y)

Added a line break before sprintf, to ease readability. It works both with and without this line break, so it's not included in the byte count. Must hit enter between the two input numbers.

Stewie Griffin

Posted 2015-08-30T22:24:24.770

Reputation: 43 471

2Very clever use of sprintf! – Luis Mendo – 2015-08-31T10:48:37.070

4

GolfScript, 61 bytes

\.@.@="equal to "{.@.@>"greater""less"if" than "+}if" is "\+@

Expects 2 integers on the stack. Try it online.

How it works:

  • \.@.@ - A and B are already on the stack, and this code piece makes the stack look like this: ABBA. \ swaps the two top items on the stack, . duplicates the top item, and @ rotates the 3 top items (1 2 3 -> 2 3 1).

  • Then, three items are pushed to the stack: the = sign, "equal to ", and the block between {}. The if statement does this: if the first argument evaluates to true, it executes the first code block (the second argument), otherwise, the second code block (the third argument). So if A and B are equal, it will push "equal to " on the stack. If they are not equal, it will execute the code between the block. Note that = pops the two top items from the stack, so now the stack looks like AB.

  • Inside the block, you first see .@.@. Before these commands, the stack looks like AB, and after, the stack looks like BAAB. The commands are similar as the ones mentioned above.

  • Then, there's another if statement. This time, it checks whether A > B, and if true, it pushes "greater" on the stack. Else, it pushes "less" on the stack. After pushing one of these two, it will push " than " on the stack and concatenate it with the previous pushed string. > also pops the two top items of the stack, so now the stack looks like BA"string".

  • The next three commands are: " is "\+. " is " pushes that string on the stack (stack looks like BA"string"" is "), \ swaps the two top items (stack looks like BA" is ""string"), and + concatenates the two top items (stack looks like BA" is string").

  • The last command, @, rotates the three stack items, so the stack now looks like: A" is string"B. GolfScript automatically prints the stack values on STDOUT once the program terminates, so then you get the desired output.

ProgramFOX

Posted 2015-08-30T22:24:24.770

Reputation: 8 017

4

Bash, 76

a=(less\ than equal\ to greater\ than)
echo $1 is ${a[($1>$2)-($1<$2)+1]} $2

Digital Trauma

Posted 2015-08-30T22:24:24.770

Reputation: 64 644

4

Fortran, 129

Fortran arithmetic if is perfect for this challenge

Test: ideone

read(*,*)i,j
if(i-j)1,2,3
1 print*,i," is less than",j
stop
2 print*,j," is equal to",j
stop
3 print*,i," is greater than",j
end

edc65

Posted 2015-08-30T22:24:24.770

Reputation: 31 086

3

Fourier, 147 74 bytes

Non-competing because string printing is newer than this challenge

I~AoI~B` is `<A{1}{`greater than`}A<B{1}{`less than`}A{B}{`equal to`}` `Bo

Try it on FourIDE!

Dunno why I didn't allow printing before... It makes the code readable and is great for golfing

Beta Decay

Posted 2015-08-30T22:24:24.770

Reputation: 21 478

You should be able to save by assigning common letters like 101 and 116 to variables, right? I'm not sure how/if variable scope is handled. – Geobits – 2015-08-31T13:43:55.880

@Geobits There are no local scopes in Fourier, so yeah, I'll work on that – Beta Decay – 2015-08-31T15:40:53.447

@Geobits Golfed it a bit more using variables – Beta Decay – 2015-08-31T16:06:30.277

3

Bash, 94 86 bytes (saved eight bytes thanks to Digital Trauma)

p=equal;q=than;(($1>$2))&&p=greater&&[ ]||(($1<$2))&&p=less||q=to;echo $1 is $p $q $2

Test (on Linux):

echo 'p=equal;q=than;(($1>$2))&&p=greater&&[ ]||(($1<$2))&&p=less||q=to;echo $1 is $p $q $2' > cmp.sh
chmod +x cmp.sh
./cmp.sh 10 12
10 is less than 12

The use of [ ] after p=greater is to prevent || operator from being evaluated before = in the expression ...&&p=greater||(($1<$2))... (the operator precedence!).

The alternative would be using brackets around (($1>$2))&&p=greater and (($1<$2))&&p=less , but brackets make inner scope for variables, so p would be left unaltered.

pawel.boczarski

Posted 2015-08-30T22:24:24.770

Reputation: 1 243

1p=equal;q=than;(($1>$2))&&p=greater&&[ ]||(($1<$2))&&p=less||q=to;echo $1 is $p $q $2 – Digital Trauma – 2015-09-01T01:57:19.417

3

IA-32 machine code + linux, 107 bytes

Hexdump of the code:

60 89 e5 89 d0 e8 51 00 00 00 4c c6 04 24 20 38
d1 74 20 68 74 68 61 6e 4c c6 04 24 20 72 0d 68
61 74 65 72 68 20 67 72 65 44 eb 11 68 6c 65 73
73 eb 0a 68 6c 20 74 6f 68 65 71 75 61 68 20 69
73 20 88 c8 e8 12 00 00 00 89 ea 29 e2 89 e1 31
db 43 8d 43 03 cd 80 89 ec 61 c3 5b d4 0a 4c 04
30 88 04 24 c1 e8 08 75 f3 ff e3

Because of hardware limitations, the code works with numbers in the range 0...255.

Source code (can be assembled with gcc):

    .globl print_it
    .text
    .align 16
print_it:
    pushal;
    mov %esp, %ebp; // save esp (stack pointer)
    mov %edx, %eax; // put second number in al
    call prepend;   // convert al to string

    dec %esp;       // write ...
    movb $' ', (%esp); // ... a space
    cmp %dl, %cl;   // compare the numbers
    je equal;       // if equal, goto there

    push $0x6e616874; // write "than"
    dec %esp;       // write ...
    movb $' ', (%esp); // ... a space
    jb less;        // if below, goto there

greater:
    push $0x72657461; // write "ater"
    push $0x65726720; // write " gre"
    inc %esp;         // remove a space
    jmp finish;     // bypass the code for "less than"

less:
    push $0x7373656c; // write "less"
    jmp finish;     // bypass the code for "equal"

equal:
    push $0x6f74206c; // write "l to"
    push $0x61757165; // write "equa"

finish:
    push $0x20736920; // write " is "

    mov %cl, %al;   // put first number in al
    call prepend;   // convert al to string

    mov %ebp, %edx; // calculate the length ...
    sub %esp, %edx; // ... of the output message
    mov %esp, %ecx; // address of the message
    xor %ebx, %ebx; // set ebx to ...
    inc %ebx;       // ... 1 (i.e. stdout)
    lea 3(%ebx), %eax; // set eax=4 (syscall "write")
    int $0x80;      // do the system call
    mov %ebp, %esp; // restore the stack pointer
    popal;          // restore other registers
    ret;            // return

prepend:            // writes al converted to string
    pop %ebx;       // remove return address from the stack
appendloop:
    aam;            // calculate a digit in al, rest in ah
    dec %esp;
    add $'0', %al;  // convert the digit to ASCII
    mov %al, (%esp);// write the digit
    shr $8, %eax;   // replace al by ah; check if zero
    jnz appendloop; // nonzero? repeat
    jmp *%ebx;      // return

This is some serious abuse of the stack! The code builds the output message on the stack, from the end to the beginning. To write 4 bytes, it uses a single push instruction. To write 1 byte, it uses two instructions:

dec %esp
mov %al, (%esp);

By luck, most of the fragments to write are 4 bytes. One of them ("gre" in "greater") is 3 bytes; it's handled by pushing 4 bytes and removing one afterwards:

inc %esp

The routine that writes numbers in decimal form uses the aam instruction to divide ax by 10 repeatedly. It's advantageous that it calculates the digits from right to left!


Since there are two numbers to write, the code uses a subroutine, which is called twice. However, because the subroutine writes the results on the stack, it uses a register to hold the return address.


C code that calls the machine code above:

include <stdio.h>

void print_it(int, int) __attribute__((fastcall));

int main()
{
    print_it(90, 102);
    puts("");
    print_it(78, 0);
    puts("");
    print_it(222, 222);
    puts("");
    return 0;
}

Output:

90 is less than 102
78 is greater than 0
222 is equal to 222

anatolyg

Posted 2015-08-30T22:24:24.770

Reputation: 10 719

3

ShortScript, 98 bytes

←Α
←Β
↑Γαis
↔α>β→γgreater thanβ
↔α<β→γless thanβ
↔α|β→γequal toβ

This answer is non-competing, since ShortScript was published after this challenge.

YourDeathIsComing

Posted 2015-08-30T22:24:24.770

Reputation: 71

2

C, 155 136 127 83 bytes

f(a,b){printf("%d is %s %d\n",a,a>b?"greater than":a<b?"less than":"equal to",b);}

Mauren

Posted 2015-08-30T22:24:24.770

Reputation: 121

5You can make this much shorter - rename argc and argv, define both a and b in one line, skip the argc check, and more. – ugoren – 2015-08-31T07:18:17.110

1Note that the requirement is either a complete program or a function. A function would be much shorter. – ugoren – 2015-08-31T12:41:12.407

@ugoren I was not sure whether it could be a function, so I decided to write a complete program. I'm gonna refactor it. Thank you again! – Mauren – 2015-08-31T12:45:12.523

2

C# 6, 113 103 100 95 bytes

void C(int a,int b){System.Console.Write($"{a} is {a-b:greater than;less than;equal to} {b}");}

Thanks to edc65 for saving 13 bytes and to cell001uk for saving 5 bytes using C# 6's interpolated strings!

ProgramFOX

Posted 2015-08-30T22:24:24.770

Reputation: 8 017

Save 10 bytes void C(int a,int b){System.Console.Write("A is {0} B",a==b?"equal to":a>b?"greater than":"less than");} – edc65 – 2015-08-31T09:08:31.337

@edc65 Nice, thanks! – ProgramFOX – 2015-08-31T09:15:54.880

I love C# formatting: Write("{0} is {1:greater than;less than;equal to} {2}",a,a-b,b) – edc65 – 2015-08-31T09:52:50.923

@edc65 Woah, that's awesome! Thanks! Also thanks for reminding me that A and B have to be replaced by their values, I totally overlooked that >_> – ProgramFOX – 2015-08-31T10:15:05.157

@edc65 I can't find the documentation for that kind of format string.. could you shed some light? – Rob – 2015-09-01T03:42:23.863

2

JavaScript, 151 104 100 95 92 bytes

a+=prompt()
b+=prompt()
alert(a+" is "+(a>b?"greater than ":a<b?"lesser than ":"equal to ")+b)

I managed to shorten with help of edc65

user41805

Posted 2015-08-30T22:24:24.770

Reputation: 16 320

I am a JavaScript newbie... – user41805 – 2015-08-31T09:32:29.190

May I ask what you are using to find your score? – Beta Decay – 2015-08-31T09:34:02.043

Not it's broken (syntax error). Just try before posting – edc65 – 2015-08-31T09:34:02.530

Is there an error now? – user41805 – 2015-08-31T09:38:47.577

Welcome to PPCG! It's a competition for shortest code, so you don't need to follow the best practices, but your code have to be correct. Now, it's not because there is (still) a missing ?. On the other hand, var is not needed. – edc65 – 2015-08-31T09:39:26.790

This could be a=+prompt(),b=+prompt();alert(a+(a>b?" is greater than ":a<b?" is lesser than ":" is equal to ")+b) 99 bytes – edc65 – 2015-08-31T09:40:42.070

You can write a function and use ES6 to remove some bytes for input. – jimmy23013 – 2015-08-31T09:55:36.943

@jimmy23013 Isn't just going to make it the same as the pre-existing ES6 answer? – Beta Decay – 2015-08-31T09:57:54.177

@BetaDecay Well, yes... But two prompt()s are so long... – jimmy23013 – 2015-08-31T10:07:26.690

Will it be ok if the brackets surrounding the if-statement were taken out? – user41805 – 2015-08-31T10:18:12.570

No. But go the console panel of your browser (press F12) and try yourself. – edc65 – 2015-08-31T10:32:12.450

If I take out the tildas (~) in your answer, please do not put them back in. – Beta Decay – 2015-08-31T21:00:31.947

@edc65 you suggested that I have a+=prompt() instead of var a = prompt(). But how does that work, how can a get a value if it was not initialised? – user41805 – 2015-09-01T04:39:42.310

No I suggested a = +prompt(). prompt() return a string, the + convert to a number. You have to compare numbers, not strings: the string "9" is greater than the string "123", while the number 9 is less than the number 123 – edc65 – 2015-09-01T04:50:01.007

@edc65 but how does aget initialised – user41805 – 2015-09-01T04:55:52.667

1a = expression. That is an initialisation. var a is declaring the variable a. You have to use it in real code for a lot of good reasons. But it's optional in javascript and avoiding var you save 4 charactes – edc65 – 2015-09-01T05:02:53.343

2

Haskell, 87 bytes

One byte shorter than Otomo's approach.

a?b=show a++" is "++["less than ","equal to ","greater than "]!!(1+signum(a-b))++show b

Lynn

Posted 2015-08-30T22:24:24.770

Reputation: 55 648

Nice solution. :) – Otomo – 2015-09-01T06:58:00.417

2

Lua, 118 bytes

I don't see enough Lua answers here so...

function f(a,b)print(a>b and a.." is greater than "..b or a==b and a.." is equal to "..b or a.." is less than "..b)end

Ungolfed:

function f(a,b)
    print(a>b and a.." is greater than "..b or a==b and a.." is equal to "..b or a.." is less than "..b)
end

Nikolai97

Posted 2015-08-30T22:24:24.770

Reputation: 653

Welcome to PPCG! – Dennis – 2015-09-01T03:30:41.920

2

Python 2, 78 bytes

I love how cmp() is really useful, but it was removed in Python 3.

Using an anonymous function:

lambda a,b:`a`+' is '+['equal to ','greater than ','less than '][cmp(a,b)]+`b`

Not using a function (79 bytes):

a,b=input();print a,'is %s'%['equal to','greater than','less than'][cmp(a,b)],b

mbomb007

Posted 2015-08-30T22:24:24.770

Reputation: 21 944

Isn't this a dupe of @TheNumberOne's answer?

– Beta Decay – 2015-09-01T16:43:23.250

@BetaDecay Nope. They are different. Read my comment on that answer. – mbomb007 – 2015-09-01T18:38:20.393

1

05AB1E, 30 bytes

.S“ž‰€„†ª€ëîØ€ë“#2ôè¹'€ˆ.À`²ðý

Try it online!

Erik the Outgolfer

Posted 2015-08-30T22:24:24.770

Reputation: 38 134

1

Befunge-93, 82 bytes

<v"equal to "$_v#!\!`0:\0:-&,,,"is ".::&
 v "less than "_" naht retaerg"
@>:#,_$-.

Try it online!

Jo King

Posted 2015-08-30T22:24:24.770

Reputation: 38 234

1

Pyth, 57 55 53 bytes

AQjd[G"is"@c"equal to
greater than
less than"b._-GHH)

This basically does:

["less than", "greater than", "equal to"][sign_of(A-B)]

Saved 2 bytes thanks to @AlexA.'s suggestion of using A instead of J and K and another 2 bytes by replacing the whole addition mess with a simpler subtraction.

Live demo and test cases.

55-byte version

AQjd[G"is"@c"less than
greater than
equal to"b+gGHqGHH)

Live demo and test cases.

57-byte version:

jd[JhQ"is"@c"less than
greater than
equal to"b+gJKeQqJKK)

Live demo and test cases.

kirbyfan64sos

Posted 2015-08-30T22:24:24.770

Reputation: 8 730

One byte shorter: AQs[Gd"is"d?<GH"less than"?>GH"greater than""equal to"dH – Alex A. – 2015-08-31T00:12:28.027

@AlexA. I just used the suggestion of A instead of J and K, which saved 2 bytes. – kirbyfan64sos – 2015-08-31T00:17:08.660

1

rs, 105 bytes

(\d+) (\d+)/\1 is (_)^^(\1) (_)^^(\2) \2
 (_+) \1_+/ less than
 (_+) \1 / equal to 
_+ _+/greater than

The trailing and preceding whitespace is very important!

Live demo and all test cases.

kirbyfan64sos

Posted 2015-08-30T22:24:24.770

Reputation: 8 730

1

O, 67 bytes

jJ" is ""greater than""less than""equal to"JjK-.e\1<+{@}d;;' K++++p

Live demo.

kirbyfan64sos

Posted 2015-08-30T22:24:24.770

Reputation: 8 730

1

SWI-Prolog, 94 bytes

a(A,B):-(((A>B,C=greater;A<B,C=less),D=than);C=equal,D=to),writef("%t is %t %t %t",[A,C,D,B]).

Fatalize

Posted 2015-08-30T22:24:24.770

Reputation: 32 976

1

Haskell, 97 94 88 bytes

a!b|a>b="greater than "|a<b="less than "|1<3="equal to "
a#b=show a++" is "++a!b++show b

thanks to nimi

94 byte version:

d a|a>0="greater than "|a<0="less than "|1<3="equal to "
c a b=show a++" is "++d(a-b)++show b

97 byte version:

d a b|a>b=" greater than "|a<b=" less than "|1<3=" equal to "
c a b=show a++" is"++d a b++show b

my first time golfing :) (tested with ghci, size determined with du and stat)

Otomo

Posted 2015-08-30T22:24:24.770

Reputation: 181

1You can save a few bytes by turning the functions d and c into operators, e.g. d becomes a!b|a>b=... and c becomes a#b=show a++" is"++a!b++show b. Example run: 41#51. – nimi – 2015-08-31T16:29:40.700

You need one more fix: d(a-b) --> a!b, and this byte counter tells me your score is then 88.

– Lynn – 2015-09-01T01:32:28.980

Thx - i missed that – Otomo – 2015-09-01T06:06:12.843

1

Ruby 1.9+, 73 71 70 68 bytes

->a,b{[a,b]*" is #{%w{equal\ to greater\ than less\ than}[a<=>b]} "}

Ibrahim Tencer

Posted 2015-08-30T22:24:24.770

Reputation: 321

11 character shorter with word array: %w{equal\ to greater\ than less\ than} – manatwork – 2015-08-31T12:10:24.023

1Can shave two more characters using Array#: `->a,b{[a,b]" is #{%w{equal\ to greater\ than less\ than}[a<=>b]} "}` – histocrat – 2015-08-31T18:56:45.107

1

Swift, 105 92 byte

func c(a:Int, b:Int){println("A is",(a==b ?"equal to":(a<b ?"less":"greater")," than"),"B")}

even shorter with Swift 2.0 (103 90 byte)

func c(a:Int, b:Int){print("A is",(a==b ?"equal to":(a<b ?"less":"greater")," than"),"B")}

OutOfBounds

Posted 2015-08-30T22:24:24.770

Reputation: 21

1

Processing, 92 bytes

void c(int a,int b){print(a+" is "+(a>b?"greater than ":a<b?"lesser than ":"equal to ")+b);}

user41805

Posted 2015-08-30T22:24:24.770

Reputation: 16 320

1

PHP, 103 100 bytes

103 byte version.

function c($a,$b){echo "A is ".($a==$b?"equal to":($a>$b?"greater than":($a<$b?"less than":"")))." B";}

100 byte version (thanks jrenk)

<?php function c($i,$u){echo$i.' is '.($i>$u?'greater than ':($i==$u?'equal to ':'less than ')).$u;}

ale8oneboy

Posted 2015-08-30T22:24:24.770

Reputation: 11

I think you should replace "A" and "B" in the output with the numbers you get from the input. – jrenk – 2015-09-01T06:56:05.247

You should count the "<?php" opening tag to your byte count. You can save a few bytes by just using ":" for 'less than' since it's the last case that could happen. Look here.

– jrenk – 2015-09-01T07:25:51.490

Awesome. Thanks for your help! – ale8oneboy – 2015-09-01T11:35:30.220

you can shorten it by 1 byte if you use: echo"$i is " instead of echo$i.' is ' – Dan – 2015-09-01T15:34:05.937

1

PHP, 88 bytes


PHP function, 88 bytes:

function a($a,$b){echo"$a is ",$a-$b?($a>$b?"greater":"less")." than":"equal to"," $b";}
function b($a,$b){echo"$a is ",$a-$b?$a>$b?"greater than":"less than":"equal to"," $b";}
function c($a,$b){echo"$a is ",$a-$b?($a>$b?"greater":"less")." than $b":"equal to $b";}

Note than $a-$b can be replaced by $a^$b.


Full program, 89 bytes:

<?=$a=$argv[1]," is ",$a-($b=$argv[2])?($a>$b?"greater":"less")." than $b":"equal to $b";

I used:

Benoit Esnard

Posted 2015-08-30T22:24:24.770

Reputation: 311

1

JavaScript, 84 bytes

f=function(a,b){alert(a+' is '+(a-b?(a>b?'greater':'less')+' than ':'equal to ')+b)}

curiousdannii

Posted 2015-08-30T22:24:24.770

Reputation: 657

1

APL (Dyalog Unicode), 56 bytesSBCS

Anonymous infix lambda.

{∊⍺'is ','less than' 'equal to' 'greater than'[2+×⍺-⍵]⍵}

Try it online!

{} "dfn"; left argument is and right argument is :

 the right argument to the right of
'less than' 'equal to' 'greater than'[] this list of three strings indexed by:
  ⍺-⍵ left argument minus right argument
  × sign of that
  2+ add two to that

⍺'is ', prepend the left argument and the string "is "

ϵnlist (flatten)

Adám

Posted 2015-08-30T22:24:24.770

Reputation: 37 779

1

Rust, 271 bytes

use std::cmp::Ordering::*;fn main(){let v:Vec<String>=std::env::args().collect();let a:u8=v[1].parse().unwrap();let b:u8=v[2].parse().unwrap();print!("{} is ",a);print!("{}", match a.cmp(&b) {Less=>"less than",Equal=>"equal to",Greater=>"greater than"});print!(" {}",b);}

Pretty printed version:

use std::cmp::Ordering::*;

fn main() {
    let v:Vec<String> = std::env::args().collect();
    let a:u8 = v[1].parse().unwrap();
    let b:u8 = v[2].parse().unwrap();
    print!("{} is ", a);
    print!("{}", match a.cmp(&b) {
        Less => "less than",
        Equal => "equal to",
        Greater => "greater than"
    });
    print!(" {}", b);
}

XAMPP Rocky

Posted 2015-08-30T22:24:24.770

Reputation: 111

Updated to match that – XAMPP Rocky – 2015-09-03T19:36:35.083

That's great, and welcome to PPCG :) – Beta Decay – 2015-09-03T19:51:30.700

0

05AB1E, 38 36 bytes

(non-competing as question predates the language)

²¹.S>ð“îØ€ë
ž‰€„
†ª€ë“«¶¡è¹… is«sð²J

I'm surprised there isn't already a 05AB1E answer. You can write almost any word in 05AB1E with just 2 bytes.

Try it online!

Okx

Posted 2015-08-30T22:24:24.770

Reputation: 15 025

0

SmileBASIC, 84 bytes

INPUT A,B
S=B-A?A;" is ";MID$("greater equal toless ",SGN(S)*8+8,8);"than"*!!S;" ";B

12Me21

Posted 2015-08-30T22:24:24.770

Reputation: 6 110

0

Noether, 91 79 bytes

Non-competing

I~aP" is "PI~b{ab=}{"equal to"P}{ab>}{"greater than"P}{ab<}{"less than"P}" "PbP

Try it here!

Note that while Noether is based heavily on Fourier, I have sacrificed golfability for functionality.

Beta Decay

Posted 2015-08-30T22:24:24.770

Reputation: 21 478

0

PowerShell, 71 Bytes

param($a,$b)"$a is $($a-$b|% T*g "greater than;less than;equal to") $b"

an update to the existing powershell answer from 2 years ago.

colsw

Posted 2015-08-30T22:24:24.770

Reputation: 3 195

0

J, 64 bytes

9;:inv@A.;&":,'is'~.@;cut@'equal to greater than less'{~1 2*>-<

Try it online!

equal to is joined by a non-break space.

1 2*>-<: –1, –2 if less; 0, 0 if equal; 1, 2 if greater than
;&":,'is'~.@; prepend is, then prepend A and B. Because 0, 0 yields equal to,equal to, there’s a ~. to remove duplicates.
9 A. to shuffle B to the last position.
;:inv@ join by spaces

FrownyFrog

Posted 2015-08-30T22:24:24.770

Reputation: 3 112

0

C++, 109 bytes

#include<cstdio>
int x(int a,int b){printf("%d is %s %d",a,a>b?"greater than":a<b?"less than":"equal to",b);}

EvgeniyZh

Posted 2015-08-30T22:24:24.770

Reputation: 141

0

Common Lisp, 92 bytes

(lambda(a b)(format t"~A is ~[less than~;equal to~;greater than~] ~A"a(1+(signum(- a b)))b))

More readably:

(lambda(a b)
  (format t "~A is ~[less than~;equal to~;greater than~] ~A"
  a                   ; first ~A
  (1+(signum(- a b))) ; gives 0, 1 or 2 which selects a clause in ~[ ~]
  b                   ; second ~A
))

coredump

Posted 2015-08-30T22:24:24.770

Reputation: 6 292

1Good, but reversed. I ran it like ((lambda(a b)(format t"~A is ~[less than~;equal to~;greater than~] ~A"a(1+(signum(- b a)))b)) 10 20) in CLISP console and it yields 10 is greater than 20. – pawel.boczarski – 2015-08-31T15:37:12.343

@pawel.boczarski Thanks a lot. – coredump – 2015-08-31T18:54:27.120

0

Inform 7, 109 bytes

To(A - value)T(B - value):say "[A] is [if A is B]equal to [else if A > B]greater than [else]less than ";say B

This defines a phrase used as 1 T 2;.

curiousdannii

Posted 2015-08-30T22:24:24.770

Reputation: 657

0

JavaScript, 92 bytes

a=+prompt(),b=+prompt();alert(a+" is "+(a>b?"greater than ":a<b?"less than ":"equal to ")+b)

Tiago Sippert

Posted 2015-08-30T22:24:24.770

Reputation: 101

0

PHP 7, 91 bytes

<?=$a=$argv[1],[~ß–ŒßšŽŠž“ß‹ß,~ß–Œß“šŒŒß‹—ž‘ß][($b=$argv[2])<=>$a]?:~ß–Œß˜šž‹šß‹—ž‘ß,$b;

Usage:

Save as ANSI in file.php and run:

php -derror_reporting=~E_NOTICE file.php A B

Is suppressing notices via CLI flag considered cheating? If so, here is a version that works with full error reporting, (93 Bytes)

<?=$a=$argv[1],@[~ß–ŒßšŽŠž“ß‹ß,~ß–Œß“šŒŒß‹—ž‘ß][($b=$argv[2])<=>$a]?:" is greater than ",$b;

Some Explanation

For the string constants, I used undefined constants and bitwise invert them with ~. PHP replaces undefined constants with the name of the constant (foo => "foo") and allows special characters in constant names. This way you can save a byte even for strings with whitespace. Example: => " ")

The spaceship operator <=> returns 0 if the operands are equal, -1 if the left operand is less than the right operand and 1 if the left operand is greater than the left operand. I use this as array index, to get " is equal to " and " is less than ". For the non-existing array key -1 the result is null and thanks to ?: we get " is greater than " in this case.

Fabian Schmengler

Posted 2015-08-30T22:24:24.770

Reputation: 1 972

As long as the errors aren't output to STDOUT, suppressing them is fine – Beta Decay – 2015-08-31T21:27:20.527

0

PowerShell, 98 85 Bytes

(Thanks to tomkandy for the huge assist on the param and reminding me that PowerShell likes inline subexpression parsing, so go ahead and use it)

param($a,$b);"$a is $(@("equal to","greater than","less than")[$a.CompareTo($b)]) $b"

Essentially the same, just trimmed down quite a bit.


(Original below)

Decently competitive, I was somewhat surprised. Again, the $ character and taking input is the downfall.

$a=$args[0];$b=$args[1];"$a is "+@("equal to","greater than","less than")[$a.CompareTo(+$b)]+" $b"

(Creating a function of two arguments is one byte longer than taking command-line input of two arguments, thanks to the } at the end)

function r{param($a,$b);<doing_stuff>}
$a=$args[0];$b=$args[1];<doing_stuff>

Expanded:

$a=$args[0]
$b=$args[1]
"$a is " + @("equal to","greater than","less than")[$a.CompareTo(+$b)] + " $b"

Similar in concept to some other languages present, this is utilizing a feature of x.CompareTo(y), which returns -1 if x<y, 0 if x=y, and 1 if x>y. We take that result and pull out the appropriate value from a dynamic array we just created, leveraging the fact that [-1] stands for the last item in the array.

Do note the + inside the CompareTo(+$b) statement -- an explicit cast to an Integer. If we left that off, it would try to utilize the String comparison instead, which yields odd behavior.

AdmBorkBork

Posted 2015-08-30T22:24:24.770

Reputation: 41 581

You can get this down to 85 bytes with param - you don't need to use function to do so, param will work in a script - and by using subexpressions param($a,$b);"$a is $(@("equal to","greater than","less than")[$a.CompareTo($b)]) $b" – tomkandy – 2015-09-02T16:41:38.307

Thanks @tomkandy ... I keep forgetting about the inline sub-expression expansion. And this is honestly the first I've come across using param not inside a function block; I've always stuck with $args ... guess that's what I get for being trained on VBScript and using objArg everywhere ... – AdmBorkBork – 2015-09-02T17:13:58.483

0

Swift 2.0, 87 bytes

func g(a:Int,b:Int){print("A is",a==b ?"equal to":a<b ?"less than":"greater than","B")}

GoatInTheMachine

Posted 2015-08-30T22:24:24.770

Reputation: 463

0

beeswax, 68 chars

Non-competing answer, as I finished creating beeswax in December 2015, long after the start of the challenge.

The natural number range of beeswax is 64 bit unsigned integers, so this should be a valid solution. I’ll post a solution for 64 bit signed integers soon.

_T~T~{` is `Kp`equal to `{
p`ht ssel`#L~EL#~`greater than `{
>`an `{

You can clone the full and latest version of my beeswax interpreter, including examples and language specification from my GitHub repo.

M L

Posted 2015-08-30T22:24:24.770

Reputation: 2 865

0

Julia, 90 79 chars

Arrays in Julia use 1-based indexing, so adding 2 to the cmp function is necessary for proper access to the array.

c(a,b)=print(a," is ",["less than ","equal to ","greater than "][cmp(a,b)+2],b)

Result:

julia> c(2,2)                       
2 is equal to 2                     
julia> c(1654654,0)                 
1654654 is greater than 0           
julia> c(-99999999999,-654654654)   
-99999999999 is less than -654654654

M L

Posted 2015-08-30T22:24:24.770

Reputation: 2 865

0

Mouse-2002, 73 bytes

Uses variables (lame, I know).

?a:?b:"A is "a.b.>["greater than"]a.b.<["less than"]a.b.=["equal to"]" B"

Explained:

? a: ? b:  ~ store input in a , b
"A is "               ~ print
a. b. &gt [           ~ testif
  "greater than"      ~ print
]
a. b. &lt [           ~ rinse && repeat
  "less than"
]
a. b. = [
  "equal to"
]
" B"

Pure stack version: 96 95 bytes

I had fun writing this one. It would be a LOT shorter if Mouse had a 2dup instruction, but I implemented it myself instead.

??#D;#D;"A is ">["greater than"]<["less than"]=["equal to"]" B"
$D&swap &dup &rot &rot &over @

How this works:

? ? #D; #D; ~ get some input, then 2dup twice
"A is "                ~ print this
&gt [                  ~ test if gtr
  "greater than"       ~ print this
]                      ~ fallthrough
&lt [                  ~ repeat for next two conditions
  "less than"
]
= [
  "equal to"
]
" B"

$D       ~ def D():
 &swap        ~ ( x y -- y x )
 &dup         ~        ( y x -- y x x )
 &rot         ~               ( y x x -- x x y )
 &rot         ~                        ( x x y -- x y x )
 &over        ~                                 ( x y x -- x y x y )
@

We need the 2dup instruction because comparison pops. Stack operations FTW!

Edit: for the same stack effect but a byte less, the second swap in the 2dup implementation was changed to rot.

cat

Posted 2015-08-30T22:24:24.770

Reputation: 4 989

You have to actually print the numbers, not just "A" and "B". – FlipTack – 2017-02-01T20:42:38.390

@FlipTack Oh, well, the spec is wildly unclear and other answers have the same behaviour. I'll fix it later – cat – 2017-02-03T16:53:59.633

0

Perl 6, 74 bytes

->\a,\b{say a~" is {<less equal greater>[1+(a <=>b)],<than to>[a==b]} "~b} # 74

Usage:

# give it a lexical name for ease of use
my &compare = ->\a,\b{ … }

compare 1,2;
compare 2,2;
compare 3,2;

say '';

compare "{ 2²⁵⁶ }\n", "\n{ 2²⁵⁶ + 1 }"
1 is less than 2
2 is equal to 2
3 is greater than 2

115792089237316195423570985008687907853269984665640564039457584007913129639936
 is less than 
115792089237316195423570985008687907853269984665640564039457584007913129639937

Brad Gilbert b2gills

Posted 2015-08-30T22:24:24.770

Reputation: 12 713

0

Python 3, 78 bytes

Translation of TheNumberOne's, using a double conditional instead of cmp, doesn't do too badly imo.

lambda a,b:print(a,'is',[['equal to','greater than'][a>b],'less than'][a<b],b)

You can also replace cmp(a,b) with (a>b)-(a<b), but when I replaced it directly I found it one byte longer than my solution above. I also tried returning a string, instead of printing, but that was longer too.

Ogaday

Posted 2015-08-30T22:24:24.770

Reputation: 471