比较两个数字


25

挑战

鉴于两个整数A,并B作为输入,你必须写一个程序,如果输出A>BA==BA<B

整数将在您的语言支持的任何合理范围内,包括至少256个值。

您的程序可以是完整程序,也可以是函数,可以通过STDIN或函数参数进行输入。

产出

如果A>B输出

A is greater than B

如果A==B输出

A is equal to B

如果A<B输出

A is less than B

在其中替换AB为其整数值。

获奖

以字节为单位的最短程序获胜。

排行榜

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>


关于编程难题和代码高尔夫球的今天:三元语句!
Trebuchette

函数可以简单地返回解决方案而不是打印出解决方案吗?
TheNumberOne

@TheNumberOne不,他们必须打印解决方案
Beta Decay

Answers:


11

CJam,47岁

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

在线尝试

说明:

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

看起来CJam今天比Pyth短一个字节:(
orlp

根据用于读取多条输入的默认值,您可以将输入读取为[A B]]从代码中消除输入。
丹尼斯

@丹尼斯,谢谢,我曾考虑过,但不确定。
2015年

@orlp现在有2个字节,这就是一个微笑的原因,而不是皱眉:)
aditsu

适当地,您的代码实际上包含以下形式的笑脸~_~...
Darrel Hoffman 2015年

19

Python 2,95 94 76字节

输入必须以逗号分隔。

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

我很感兴趣,您能解释一下什么cmp(A,B)是什么吗?:)
Beta Decay 2015年

2
@ BetaDecay,docs.python.org / 2 / library / functions.html#cmp。“比较两个对象x和y并根据结果返回整数。如果x <y,则返回值为负;如果x == y,则返回值为零;如果x> y,则返回严格为正。” 在cPython 2.7.6中,这些整数的值分别为-1、0、1。函数的定义并不要求如此,因此,一个学徒可能会坚持在此处给出python的确切实现和版本,而不仅仅是“ Python 2”,但是我希望大多数实现在这里的行为都相同。
ymbirtt

我只想让你知道我没有复制你的答案来提出我的想法。我刚才看到它们有多近。当我写我的代码时,我在运行代码段时遇到了麻烦,而且我可能发誓那里还没有Python的答案(一定错过了第二页)。我完全独立地编写了它,这很奇怪。
mbomb007'9

@ Sp3000我检查了它,它在Python 2.7.6中工作得很好
ML

1
@ML我的评论指向的是以前的修订,但是由于它已经过时了,所以我删除了评论
Sp3000,2016年

10

迷宫180间 152 149字节

<
?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.{!@

编辑:通过重新使用托管剃掉3个字节10之间101103108(的字符代码egl)。下面的解释并没有反映出这一点,但这并不是实质性的变化。

说明

在保存字节以打印字符串方面,我们无能为力,这将是很长的线性段。因此,打高尔夫球的主要挑战是避免大量不必要的空白。这意味着我们希望线性部分从最左侧的列“辐射出去”。通过重用打印的代码,我们还可以节省更多钱than B。因此,让我们在这里看一下控制流程:

该程序从网格旋转命令开始<。这会将当前行周期性地向左移动带有IP的左侧,因此我们得到以下信息:

                                                     <
?.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.{!@

现在IP位于一个隔离的单元上,因此它一次又一次地执行相同的命令,而<行进向左移动直到...

                    <
?.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.{!@

此时,IP尚有待解决的地方,并从右到左执行第一个线性部分(第二行)。它的作用是阅读A,复制,打印。在数字,打印is(和空格)之间使用定界字符。然后阅读B,复制并A从中减去-

在这一点上,我们首先击中了“叉路”。如果产生差异0,则IP继续直接向底部分支移动。该分支仅打印equal to然后B

否则,IP会向两个无操作状态左转 ""。然后还有另一个叉子。如果差异为负,则IP向左较长的上分支转移另一个。该分支仅打印greater than然后B

如果差异为正,则IP移至较低的分支,该分支打印less。现在我们要重用than另一个分支中的。但是同时,我们不想以后再连接两个分支,因为我们需要一堆不必要的空间。取而代之的是,我们使用一些无操作来使下分支与than上分支的开始位置对齐,然后使用^以下命令再次操作源:

                    <
?.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 .{!@

再次,这是隔离IP,因此^再次执行,我们得到

                    <
?.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 .{!@

现在,IP可以继续向右移动thanB根据需要进行打印。


8

JavaScript(ES6),66个字节

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

定义一个匿名函数。通过f=在其之前添加进行测试,然后像调用它一样alert(f(4, 5))


不幸的是,重复的“ than”没有节省。


你确定吗?Java的答案似乎比(;)更好
Beta Decay,

3
@BetaDecay好吧,不。甚至Java答案也将重复相同的长度thanpublic void c(int a,int b){System.out.print(a+" is "+(a==b?"equal to ":a>b?"greater than ":"smaller than ")+b);}
edc65

@BetaDecay如果它实际上没有输出文本,这是一个有效的答案吗?或者,alert()应将7 for 添加到分数中。
curiousdannii 2015年

@curiousdannii哦,我知道了,是的,如果您不算alert()作代码和字节数的一部分,则这是无效的
Beta Decay

@BetaDecay哦,我没有意识到答案应该打印出来,而不是返回。如果假设REPL环境还可以,则可以在FireFox控制台中免费运行,否则我认为它可以达到
73。– jrich

8

Java中,114个 113字节或74 72 67如果我们使用拉姆达符号

感谢Kevin Cruijssen基于curry的解决方案:

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

旧的pre lambda解决方案

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

作为用户hjk在注释中的含义,如果我们使用lambda,则可以显着减少到74个字节。

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

1
聪明的压缩方式than:)
TheNumberOne

4
您可以public根据需要删除。我建议把它变成lambda。您可以在之前删除一个空格{
TheNumberOne

1
并且在使用它时,请在#Java之后添加一个逗号,以便您可以进入排行榜。;)
TNT

2
官方的问题规格是说“少”,而不是“小”。您不妨这样做并丢失三个字节!我不懂Java,但是lambda代码会打印文本还是返回文本?如果不打印,则可能不是有效答案。
curiousdannii 2015年

2
@hjk使用currying更短的lambda:a->b->a+" is "+(a==b?"equal to ":(a>b?"greater":"smaller" )+" than ")+b是的,我知道已经快两年了。;)实际上,您可以使用less而不是smaller基于挑战说明,就像我上面的两条评论所提到的那样。在这里尝试看看如何进行计算。
凯文·克鲁伊森

7

R,80字节

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

1
您可以通过将“小于”更改为“小于”来遵循上述规范,从而节省3个字节。+1(表示不使用三元运算符)。
bmark

啊,谢谢,我没听清楚!固定!
flodel

@bmarks R没有三元运算符。:P
Alex A.

@AlexA。我知道。我的意思是,到目前为止,使用列表和符号函数与其他答案有很大不同(大多数答案都使用三元运算符或类似运算符)。
bmark

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

7

Pyth, 52 49 bytes

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

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.


6

Perl,64 63字节

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

62个字节+ 1个字节(用于)-p。从STDIN接受输入,两个数字用单个空格分隔:

$ 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

怎么运行的:

<=>操作者返回-1,0或1取决于第一操作数是否小于,等于或大于第二个。方便地,Perl允许带有数组和切片的负下标,其中最后一个元素在位置-1,倒数第二个元素在位置-2,依此类推。

在代码中

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

我们使用返回值of <=>作为列表切片中的下标来获取相应的字符串,其中$`第一个数字是$' is the second.

为避免重复thanx用作占位符,并在末尾进行第二次替换。


替代解决方案,63字节

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

62个字节+ 1个字节(用于)-p。像第一个解决方案一样,从STDIN接受以空格分隔的输入。

怎么运行的:

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


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

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.


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.


2
Very clever use of sprintf!
Luis Mendo

4

Bash, 76

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

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

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.


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

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

3

ShortScript, 98 bytes

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

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


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


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

@Geobits There are no local scopes in Fourier, so yeah, I'll work on that
Beta Decay

@Geobits Golfed it a bit more using variables
Beta Decay

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);}

5
You can make this much shorter - rename argc and argv, define both a and b in one line, skip the argc check, and more.
ugoren

1
Note that the requirement is either a complete program or a function. A function would be much shorter.
ugoren

@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

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

Nice solution. :)
Otomo

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

Welcome to PPCG!
Dennis

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

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

@BetaDecay Nope. They are different. Read my comment on that answer.
mbomb007

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


I am a JavaScript newbie...
Kritixi Lithos

May I ask what you are using to find your score?
Beta Decay

Not it's broken (syntax error). Just try before posting
edc65

Is there an error now?
Kritixi Lithos

1
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
edc65

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!


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

@edc65 Nice, thanks!
ProgramFOX

I love C# formatting: Write("{0} is {1:greater than;less than;equal to} {2}",a,a-b,b)
edc65

@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



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.


One byte shorter: AQs[Gd"is"d?<GH"less than"?>GH"greater than""equal to"dH
Alex A.

@AlexA. I just used the suggestion of A instead of J and K, which saved 2 bytes.
kirbyfan64sos


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

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")}

1

Processing, 92 bytes

void c(int a,int b){print(a+" is "+(a>b?"greater than ":a<b?"lesser than ":"equal to ")+b);}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.