25
\$\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.

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\$
  • \$\begingroup\$ Today on Programming Puzzles & Code Golf: ternary statements! \$\endgroup\$ – Trebuchette Sep 1 '15 at 1:29
  • \$\begingroup\$ Can functions simply return the solution instead of printing out the solution? \$\endgroup\$ – TheNumberOne Sep 2 '15 at 14:18
  • \$\begingroup\$ @TheNumberOne No, they must print the solution \$\endgroup\$ – Beta Decay Sep 2 '15 at 16:07

56 Answers 56

1 2
1
\$\begingroup\$

Ruby 1.9+, 73 71 70 68 bytes

->a,b{[a,b]*" is #{%w{equal\ to greater\ than less\ than}[a<=>b]} "}
\$\endgroup\$
  • 1
    \$\begingroup\$ 1 character shorter with word array: %w{equal\ to greater\ than less\ than} \$\endgroup\$ – manatwork Aug 31 '15 at 12:10
  • 1
    \$\begingroup\$ Can shave two more characters using Array#*: ->a,b{[a,b]*" is #{%w{equal\ to greater\ than less\ than}[a<=>b]} "} \$\endgroup\$ – histocrat Aug 31 '15 at 18:56
1
\$\begingroup\$

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)

\$\endgroup\$
  • 1
    \$\begingroup\$ You 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. \$\endgroup\$ – nimi Aug 31 '15 at 16:29
  • \$\begingroup\$ You need one more fix: d(a-b) --> a!b, and this byte counter tells me your score is then 88. \$\endgroup\$ – Lynn Sep 1 '15 at 1:32
  • \$\begingroup\$ Thx - i missed that \$\endgroup\$ – Otomo Sep 1 '15 at 6:06
1
\$\begingroup\$

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;}
\$\endgroup\$
  • \$\begingroup\$ I think you should replace "A" and "B" in the output with the numbers you get from the input. \$\endgroup\$ – jrenk Sep 1 '15 at 6:56
  • \$\begingroup\$ 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. \$\endgroup\$ – jrenk Sep 1 '15 at 7:25
  • \$\begingroup\$ Awesome. Thanks for your help! \$\endgroup\$ – ale8oneboy Sep 1 '15 at 11:35
  • \$\begingroup\$ you can shorten it by 1 byte if you use: echo"$i is " instead of echo$i.' is ' \$\endgroup\$ – Dan Sep 1 '15 at 15:34
1
\$\begingroup\$

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:

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

JavaScript, 84 bytes

f=function(a,b){alert(a+' is '+(a-b?(a>b?'greater':'less')+' than ':'equal to ')+b)}
\$\endgroup\$
1
\$\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\$
  • \$\begingroup\$ Updated to match that \$\endgroup\$ – XAMPP Rocky Sep 3 '15 at 19:36
  • \$\begingroup\$ That's great, and welcome to PPCG :) \$\endgroup\$ – Beta Decay Sep 3 '15 at 19:51
1
\$\begingroup\$

05AB1E, 30 bytes

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

Try it online!

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

Befunge-93, 82 bytes

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

Try it online!

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

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)

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

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

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

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

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
))
\$\endgroup\$
  • 1
    \$\begingroup\$ Good, 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. \$\endgroup\$ – pawel.boczarski Aug 31 '15 at 15:37
  • \$\begingroup\$ @pawel.boczarski Thanks a lot. \$\endgroup\$ – coredump Aug 31 '15 at 18:54
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ As long as the errors aren't output to STDOUT, suppressing them is fine \$\endgroup\$ – Beta Decay Aug 31 '15 at 21:27
0
\$\begingroup\$

JavaScript, 92 bytes

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

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

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.

\$\endgroup\$
  • \$\begingroup\$ 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" \$\endgroup\$ – tomkandy Sep 2 '15 at 16:41
  • \$\begingroup\$ 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 ... \$\endgroup\$ – AdmBorkBork Sep 2 '15 at 17:13
0
\$\begingroup\$

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. > [           ~ testif
  "greater than"      ~ print
]
a. b. < [           ~ 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
> [                  ~ test if gtr
  "greater than"       ~ print this
]                      ~ fallthrough
< [                  ~ 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.

\$\endgroup\$
  • \$\begingroup\$ You have to actually print the numbers, not just "A" and "B". \$\endgroup\$ – FlipTack Feb 1 '17 at 20:42
  • \$\begingroup\$ @FlipTack Oh, well, the spec is wildly unclear and other answers have the same behaviour. I'll fix it later \$\endgroup\$ – cat Feb 3 '17 at 16:53
0
\$\begingroup\$

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.

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

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

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

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.

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

SmileBASIC, 84 bytes

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

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!

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

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.

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

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.

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

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

\$\endgroup\$
1 2

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.