Confronto tra due numeri


25

Sfida

Dati due numeri interi Ae Bcome input, è necessario scrivere un programma che emetta if A>B, A==Bo A<B.

I numeri interi saranno compresi in qualsiasi intervallo ragionevole supportato dalla tua lingua che include almeno 256 valori.

Il programma può essere un programma completo o una funzione, che accetta input tramite STDIN o argomenti di funzione.

Uscite

Se A>Buscita

A is greater than B

Se A==Buscita

A is equal to B

Se A<Buscita

A is less than B

Dove si sostituisce Ae Bper i loro valori interi.

vincente

Vince il programma più breve in byte.

Classifica

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>


Oggi su Programming Puzzles & Code Golf: dichiarazioni ternarie!
Trebuchette,

Le funzioni possono semplicemente restituire la soluzione invece di stamparla?
TheNumberOne

@TheNumberOne No, devono stampare la soluzione
Decadimento beta

Risposte:


11

CJam, 47

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

Provalo online

Spiegazione:

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

Sembra che CJam sia più corto di un byte rispetto a Pyth oggi :(
orlp

In base ai valori predefiniti per la lettura di più parti di input , è possibile leggere l'input as [A B]ed eliminare il ]dal codice.
Dennis,

@Dennis grazie, ci avevo pensato ma non ne ero sicuro.
aditsu,

@orlp 2 byte ora, ed è un motivo per sorridere, non per aggrottare le sopracciglia :)
aditsu,

Appropriato che il tuo codice contenga effettivamente uno smiley sotto forma di ~_~...
Darrel Hoffman,

19

Python 2, 95 94 76 byte

L'input deve essere separato da virgola.

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

Sono incuriosito, puoi spiegare cos'è cmp(A,B)e cosa fa? :)
Decadimento beta

2
@BetaDecay, docs.python.org/2/library/functions.html#cmp . "Confronta i due oggetti xey e restituisce un numero intero in base al risultato. Il valore restituito è negativo se x <y, zero se x == y e rigorosamente positivo se x> y.". In cPython 2.7.6, i valori di questi numeri interi sono rispettivamente -1, 0, 1. La definizione della funzione non lo impone, quindi un pedante potrebbe insistere sul fatto che l'implementazione e la versione esatta di Python sono state fornite qui anziché solo "Python 2", ma mi aspetto che la maggior parte delle implementazioni si comporti allo stesso modo qui.
ymbirtt,

Voglio solo che tu sappia che non ho copiato la tua risposta per trovare la mia . Ho appena visto quanto erano vicini. Quando ho scritto il mio ho avuto problemi con l'esecuzione dello snippet e avrei potuto giurare che non c'era già una risposta Python (devo aver perso la seconda pagina). L'ho scritto in modo completamente indipendente, abbastanza stranamente.
mbomb007,

@ Sp3000 L'ho verificato e funziona perfettamente in Python 2.7.6
ML

1
@ML Il mio commento si riferiva a una revisione passata, ma poiché è ormai obsoleto ho eliminato il commento
Sp3000,

10

Labyrinth , 180 152 149 byte

<
?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: gestito radere 3 byte riutilizzando 10tra 101, 103e 108(i codici di carattere di e, ge l). La spiegazione che segue non riflette questo, ma non è un cambiamento sostanziale.

Spiegazione

Non c'è molto che possiamo fare per salvare byte per la stampa delle stringhe, saranno solo lunghe sezioni lineari. Quindi la sfida principale nel golf è evitare grandi quantità di spazi bianchi non necessari. Ciò significa che vogliamo che le parti lineari si "irradino" dalla colonna più a sinistra. Inoltre, possiamo ottenere ulteriori risparmi riutilizzando il codice stampato than B. Diamo un'occhiata al flusso di controllo qui:

Il programma si avvia con un comando di rotazione della griglia <. Questo sposta ciclicamente la riga corrente a sinistra con l'IP su di essa, quindi otteniamo questo:

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

Ora l'IP si trova su una cella isolata, quindi esegue ripetutamente lo stesso comando mentre si <sposta ulteriormente verso sinistra fino a ...

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

A questo punto, l'IP ha un posto dove andare ed esegue la prima sezione lineare (la seconda riga) da destra a sinistra. Quello che fa è leggere A, copiare, stampare. Consuma il carattere delimitante tra numeri, stampa is(e spazi). Quindi leggi B, copialo e sottralo Ada -.

A questo punto abbiamo colpito il primo "bivio". Se la differenza ha prodotto 0, l'IP continua a muoversi dritto verso il ramo inferiore. Quel ramo semplicemente stampa equal toe poi B.

Altrimenti, l'IP gira a sinistra verso le due no-op "". Poi c'è un'altra forchetta. Se la differenza era negativa, l'IP prende un'altra a sinistra verso il ramo superiore lungo. Quel ramo semplicemente stampa greater thane poi B.

Se la differenza era positiva, l'IP prende a destra sul ramo inferiore, che stampa less. Ora vogliamo riutilizzare thanl'altro ramo. Ma allo stesso tempo non vogliamo collegare i due rami in seguito, perché avremmo bisogno di un sacco di spazi inutili. Invece usiamo alcune no-op per allineare il ramo inferiore con il punto in cui thaninizia sul ramo superiore e quindi ricominciamo a manipolare l'origine con ^:

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

Ancora una volta, questo isola l'IP, quindi ^viene eseguito di nuovo e otteniamo

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

Ora l'IP può continuare a spostarsi verso destra e stampare thane, Bse necessario.


8

JavaScript (ES6), 66 byte

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

Definisce una funzione anonima. Prova aggiungendo f=prima di esso e chiamalo comealert(f(4, 5))


Purtroppo non si possono ottenere risparmi dal ripetitivo "di".


Sei sicuro? La risposta Java sembra aggirare il;)
Decadimento beta

3
@BetaDecay bene, no. Anche la risposta Java sarebbe la stessa lunghezza ripetendo il 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,

@BetaDecay È una risposta valida se non emette effettivamente il testo? In alternativa 7 per alert()dovrebbero essere aggiunti al punteggio.
curiousdannii,

@curiousdannii Oh, vedo, sì, questo non è valido se non conti alert()come parte del tuo codice e conteggio byte
Decadimento beta

@BetaDecay oh, non mi rendevo conto che la risposta doveva essere stampata anziché appena restituita. Se supponiamo che un ambiente REPL sia ok, questo potrebbe essere eseguito gratuitamente nella console FireFox, altrimenti suppongo che sia fino a 73.
jrich

8

Java, 114 113 byte o 74 72 67 se abbiamo usato la notazione lambda

Grazie a Kevin Cruijssen per la soluzione basata sul curry:

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

Vecchia soluzione pre lambda

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

come significato di hjk dell'utente nel commento, se abbiamo usato lambda possiamo fare significativamente fino a 74 byte.

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

1
Modo intelligente di compressione than:)
TheNumberOne

4
Puoi rimuoverlo publicse vuoi. Suggerirei di trasformarlo in un lambda. È possibile rimuovere uno spazio prima di {.
TheNumberOne,

1
E mentre ci sei, aggiungi una virgola dopo #Java in modo da poter essere in classifica. ;)
TNT

2
La specifica della domanda ufficiale è dire "meno", non "più piccolo". Potresti anche farlo e perdere tre byte! Non conosco Java, ma il codice lambda stamperà il testo o lo restituirà? Se non lo stampa, probabilmente non è una risposta valida.
curiousdannii,

2
@hjk Lambda più corta usando il curry: a->b->a+" is "+(a==b?"equal to ":(a>b?"greater":"smaller" )+" than ")+bSì, sono consapevole che sono passati quasi due anni. ;) E puoi davvero usare lessinvece di smallerbasarti sulla descrizione della sfida, come menzionato dai due commenti sopra di me. Provalo qui per vedere come viene fatto il curry.
Kevin Cruijssen,

7

R, 80 byte

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

1
È possibile salvare 3 byte modificando "più piccolo di" in "meno di" per seguire le specifiche sopra. +1 per non usare un operatore ternario.
segna il

ah grazie, non l'ho preso! fisso!
flodel,

@bmarks R non ha un operatore ternario. : P
Alex A.

@AlexA. Lo so. Intendevo dire che usare un elenco e la funzione del segno era molto diverso dalle altre risposte finora (la maggior parte delle quali utilizzava operatori ternari o simili).
segna il

Destra. Per confronto, il mio primo tentativo utilizzando if / else era 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 byte

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

7

Julia, 69 66 byte

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

Questo utilizza stringa interpolazione per incorporare A, Be ternario all'interno di una singola stringa.

Salvato 3 byte grazie a Glen O.


6

Perl, 64 63 byte

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

62 byte + 1 byte per -p. Riceve input da STDIN, con i due numeri separati da un singolo spazio:

$ 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

Come funziona:

Il <=> operatore restituisce -1, 0 o 1 a seconda che il primo operando sia minore, uguale o maggiore del secondo. Convenientemente, Perl consente di utilizzare sottoscrizioni negative con matrici e sezioni, in cui l'ultimo elemento si trova nella posizione -1, il penultimo elemento si trova nella posizione -2 e così via.

Nel codice

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

usiamo il valore restituito di <=>come pedice in una sezione di elenco per ottenere la stringa corrispondente, dove $`è il primo numero ed $'è il secondo.

Per evitare la ripetizione than, xviene utilizzato come segnaposto e sostituito alla fine con una seconda sostituzione.


Soluzione alternativa, 63 byte

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

62 byte + 1 byte per -p. Riceve input separati dallo spazio da STDIN proprio come la prima soluzione.

Come funziona:

Questa soluzione utilizza anche una sezione, ma sfrutta il fatto che a differenza delle sezioni di elenco, le sezioni di matrice possono essere interpolate in stringhe (e l'RHS delle sostituzioni). Questo ci consente di eliminare il /emodificatore e le virgolette nell'operatore di sostituzione.

Il vero trucco è nel pedice slice:

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

Per i diversi valori di <=>, questo dà:

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

Quando una matrice o una porzione di matrice viene interpolata in una stringa, gli elementi vengono automaticamente uniti da $"(per impostazione predefinita, un singolo spazio).


5

Mouse , 79 byte

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

Quando si incontrano stringhe, vengono immediatamente scritte in STDOUT anziché essere messe in pila. Lo stack può contenere solo numeri interi.

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 byte

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

Prevede 2 numeri interi nello stack. Provalo online .

Come funziona:

  • \.@.@- A e B sono già in pila, e questo pezzo di codice rende l'aspetto dello stack in questo modo: ABBA. \scambia i due oggetti in cima alla pila, .duplica l'oggetto in cima e @ruota i 3 oggetti in cima ( 1 2 3-> 2 3 1).

  • Quindi, tre elementi vengono inseriti nello stack: il =segno "equal to "e il blocco tra {}. L' ifistruzione fa questo: se il primo argomento restituisce true, esegue il primo blocco di codice (il secondo argomento), altrimenti il ​​secondo blocco di codice (il terzo argomento). Quindi se A e B sono uguali, spingerà "uguale a" nello stack. Se non sono uguali, eseguirà il codice tra il blocco. Si noti che =estrae i due elementi principali dalla pila, quindi ora la pila sembra AB.

  • All'interno del blocco, vedi per la prima volta .@.@. Prima di questi comandi, appare lo stack ABe, successivamente, lo stack sembra BAAB. I comandi sono simili a quelli sopra menzionati.

  • Quindi, c'è un'altra ifaffermazione. Questa volta, controlla se A> B, e se vero, spinge "maggiore" nello stack. Altrimenti, spinge "meno" nello stack. Dopo aver spinto uno di questi due, spingerà "di" nello stack e lo concatenerà con la stringa spinta precedente. >fa anche scoppiare i due principali oggetti dello stack, quindi ora lo stack sembra BA"string".

  • I prossimi tre comandi sono: " is "\+. " is "spinge quella stringa sulla pila (sembra una pila BA"string"" is "), \scambia i due oggetti in cima (sembra la pila BA" is ""string") e +concatena i due oggetti in cima (sembra la pila BA" is string").

  • L'ultimo comando, @, ruota i tre elementi dello stack, quindi lo stack ora appare come segue: A" is string"B. GolfScript stampa automaticamente i valori dello stack su STDOUT al termine del programma, quindi si ottiene l'output desiderato.


4

MATLAB, 105 byte

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

Aggiunta un'interruzione di riga prima di sprintf, per facilitare la leggibilità. Funziona sia con che senza questa interruzione di riga, quindi non è incluso nel conteggio dei byte. Devi premere invio tra i due numeri di input.


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);}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.