30
\$\begingroup\$

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.

For example:

 A   B   Output
--  --   ------
 0   1   0 is less than 1
 5   2   5 is greater than 2
20  20   20 is equal to 20

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>

\$\endgroup\$
3
  • \$\begingroup\$ Today on Programming Puzzles & Code Golf: ternary statements! \$\endgroup\$ Commented Sep 1, 2015 at 1:29
  • \$\begingroup\$ Can functions simply return the solution instead of printing out the solution? \$\endgroup\$ Commented Sep 2, 2015 at 14:18
  • \$\begingroup\$ @TheNumberOne No, they must print the solution \$\endgroup\$
    – Beta Decay
    Commented Sep 2, 2015 at 16:07

61 Answers 61

20
\$\begingroup\$

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
\$\endgroup\$
6
  • \$\begingroup\$ I'm intrigued, can you explain what cmp(A,B) is and does? :) \$\endgroup\$
    – Beta Decay
    Commented Aug 31, 2015 at 15:58
  • 2
    \$\begingroup\$ @BetaDecay, 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. \$\endgroup\$
    – ymbirtt
    Commented Aug 31, 2015 at 16:48
  • \$\begingroup\$ 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. \$\endgroup\$
    – mbomb007
    Commented Sep 1, 2015 at 15:17
  • \$\begingroup\$ @Sp3000 I checked it ,and it works perfectly fine in Python 2.7.6 \$\endgroup\$
    – M L
    Commented Jan 3, 2016 at 3:09
  • 1
    \$\begingroup\$ @ML My comment was referring to a past revision but since it's now outdated I've deleted the comment \$\endgroup\$
    – Sp3000
    Commented Jan 3, 2016 at 10:35
11
\$\begingroup\$

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
\$\endgroup\$
5
  • \$\begingroup\$ Looks like CJam is one byte shorter than Pyth today :( \$\endgroup\$
    – orlp
    Commented Aug 31, 2015 at 2:27
  • \$\begingroup\$ According to Defaults for reading several pieces of input, you can read the input as [A B] and eliminate the ] from your code. \$\endgroup\$
    – Dennis
    Commented Aug 31, 2015 at 6:13
  • \$\begingroup\$ @Dennis thanks, I had thought about it but wasn't sure. \$\endgroup\$ Commented Aug 31, 2015 at 12:47
  • \$\begingroup\$ @orlp 2 bytes now, and that's a reason to smile, not to frown :) \$\endgroup\$ Commented Aug 31, 2015 at 12:47
  • \$\begingroup\$ Appropriate that your code actually contains a smiley in the form of ~_~... \$\endgroup\$ Commented Sep 1, 2015 at 16:13
10
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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.

\$\endgroup\$
5
  • \$\begingroup\$ Are you sure? The Java answer seems to get around the than ;) \$\endgroup\$
    – Beta Decay
    Commented Aug 31, 2015 at 9:58
  • 3
    \$\begingroup\$ @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);} \$\endgroup\$
    – edc65
    Commented Aug 31, 2015 at 10:01
  • \$\begingroup\$ @BetaDecay Is this a valid answer if it doesn't actually output the text? Alternatively 7 for alert() should be added to the score. \$\endgroup\$ Commented Sep 2, 2015 at 7:36
  • \$\begingroup\$ @curiousdannii Oh I see, yes this is invalid if you don't count alert() as part of your code and byte count \$\endgroup\$
    – Beta Decay
    Commented Sep 2, 2015 at 8:54
  • \$\begingroup\$ @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. \$\endgroup\$
    – jrich
    Commented Sep 2, 2015 at 11:14
8
\$\begingroup\$

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;
\$\endgroup\$
9
  • 1
    \$\begingroup\$ Clever way of compressing than :) \$\endgroup\$ Commented Aug 30, 2015 at 23:11
  • 4
    \$\begingroup\$ You can remove public if you want to. I would suggest making this into a lambda. You can remove the one space before the {. \$\endgroup\$ Commented Aug 30, 2015 at 23:13
  • 1
    \$\begingroup\$ And while you're at it, add a comma after #Java so you can be on the leaderboard. ;) \$\endgroup\$
    – TNT
    Commented Aug 31, 2015 at 0:02
  • 2
    \$\begingroup\$ The 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. \$\endgroup\$ Commented Sep 2, 2015 at 7:44
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ Commented Jun 1, 2017 at 12:12
7
\$\begingroup\$

R, 80 bytes

function(A,B)cat(A,"is",c("less than","equal to","greater than")[2+sign(A-B)],B)
\$\endgroup\$
5
  • 1
    \$\begingroup\$ You can save 3 bytes by changing "smaller than" to "less than" to follow the spec above. +1 for not using a ternary operator. \$\endgroup\$
    – bmarks
    Commented Aug 30, 2015 at 23:56
  • \$\begingroup\$ ah thanks, I did not catch that! fixed! \$\endgroup\$
    – flodel
    Commented Aug 30, 2015 at 23:57
  • \$\begingroup\$ @bmarks R doesn't have a ternary operator. :P \$\endgroup\$
    – Alex A.
    Commented Aug 30, 2015 at 23:58
  • \$\begingroup\$ @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). \$\endgroup\$
    – bmarks
    Commented Aug 31, 2015 at 0:01
  • \$\begingroup\$ 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). \$\endgroup\$
    – flodel
    Commented Aug 31, 2015 at 0:04
7
\$\begingroup\$

Pyth, 52 49 bytes

jdm@cd)._-FQcj"
is
equal greater less
to than
"Qb
\$\endgroup\$
7
\$\begingroup\$

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.

\$\endgroup\$
0
6
\$\begingroup\$

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

\$\endgroup\$
5
\$\begingroup\$

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

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.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Very clever use of sprintf! \$\endgroup\$
    – Luis Mendo
    Commented Aug 31, 2015 at 10:48
4
\$\begingroup\$

Bash, 76

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

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

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
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to PPCG! \$\endgroup\$
    – Dennis
    Commented Sep 1, 2015 at 3:30
3
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ p=equal;q=than;(($1>$2))&&p=greater&&[ ]||(($1<$2))&&p=less||q=to;echo $1 is $p $q $2 \$\endgroup\$ Commented Sep 1, 2015 at 1:57
3
\$\begingroup\$

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

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

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$
    – Geobits
    Commented Aug 31, 2015 at 13:43
  • \$\begingroup\$ @Geobits There are no local scopes in Fourier, so yeah, I'll work on that \$\endgroup\$
    – Beta Decay
    Commented Aug 31, 2015 at 15:40
  • \$\begingroup\$ @Geobits Golfed it a bit more using variables \$\endgroup\$
    – Beta Decay
    Commented Aug 31, 2015 at 16:06
3
\$\begingroup\$

ShortScript, 98 bytes

←Α
←Β
↑Γαis
↔α>β→γgreater thanβ
↔α<β→γless thanβ
↔α|β→γequal toβ
\$\endgroup\$
0
2
\$\begingroup\$

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);}
\$\endgroup\$
3
  • 5
    \$\begingroup\$ You can make this much shorter - rename argc and argv, define both a and b in one line, skip the argc check, and more. \$\endgroup\$
    – ugoren
    Commented Aug 31, 2015 at 7:18
  • 1
    \$\begingroup\$ Note that the requirement is either a complete program or a function. A function would be much shorter. \$\endgroup\$
    – ugoren
    Commented Aug 31, 2015 at 12:41
  • \$\begingroup\$ @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! \$\endgroup\$
    – Mauren
    Commented Aug 31, 2015 at 12:45
2
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Nice solution. :) \$\endgroup\$
    – Otomo
    Commented Sep 1, 2015 at 6:58
2
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ Isn't this a dupe of @TheNumberOne's answer? \$\endgroup\$
    – Beta Decay
    Commented Sep 1, 2015 at 16:43
  • \$\begingroup\$ @BetaDecay Nope. They are different. Read my comment on that answer. \$\endgroup\$
    – mbomb007
    Commented Sep 1, 2015 at 18:38
2
\$\begingroup\$

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

\$\endgroup\$
16
  • \$\begingroup\$ I am a JavaScript newbie... \$\endgroup\$
    – user41805
    Commented Aug 31, 2015 at 9:32
  • \$\begingroup\$ May I ask what you are using to find your score? \$\endgroup\$
    – Beta Decay
    Commented Aug 31, 2015 at 9:34
  • \$\begingroup\$ Not it's broken (syntax error). Just try before posting \$\endgroup\$
    – edc65
    Commented Aug 31, 2015 at 9:34
  • \$\begingroup\$ Is there an error now? \$\endgroup\$
    – user41805
    Commented Aug 31, 2015 at 9:38
  • 1
    \$\begingroup\$ a = 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 \$\endgroup\$
    – edc65
    Commented Sep 1, 2015 at 5:02
2
\$\begingroup\$

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!

\$\endgroup\$
6
  • \$\begingroup\$ 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");} \$\endgroup\$
    – edc65
    Commented Aug 31, 2015 at 9:08
  • \$\begingroup\$ @edc65 Nice, thanks! \$\endgroup\$
    – ProgramFOX
    Commented Aug 31, 2015 at 9:15
  • \$\begingroup\$ I love C# formatting: Write("{0} is {1:greater than;less than;equal to} {2}",a,a-b,b) \$\endgroup\$
    – edc65
    Commented Aug 31, 2015 at 9:52
  • \$\begingroup\$ @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 >_> \$\endgroup\$
    – ProgramFOX
    Commented Aug 31, 2015 at 10:15
  • 1
    \$\begingroup\$ @rob msdn.microsoft.com/it-it/library/… \$\endgroup\$
    – edc65
    Commented Sep 1, 2015 at 4:46
2
\$\begingroup\$

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);
}
\$\endgroup\$
2
  • \$\begingroup\$ Updated to match that \$\endgroup\$
    – XAMPPRocky
    Commented Sep 3, 2015 at 19:36
  • \$\begingroup\$ That's great, and welcome to PPCG :) \$\endgroup\$
    – Beta Decay
    Commented Sep 3, 2015 at 19:51
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ One byte shorter: AQs[Gd"is"d?<GH"less than"?>GH"greater than""equal to"dH \$\endgroup\$
    – Alex A.
    Commented Aug 31, 2015 at 0:12
  • \$\begingroup\$ @AlexA. I just used the suggestion of A instead of J and K, which saved 2 bytes. \$\endgroup\$ Commented Aug 31, 2015 at 0:17
1
\$\begingroup\$

O, 67 bytes

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

Live demo.

\$\endgroup\$
1
\$\begingroup\$

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]).
\$\endgroup\$
1
\$\begingroup\$

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

Your Answer

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

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