# Compare two numbers given as strings

I have a problem at work. I need to compare two numbers that come as strings from two different databases. The numbers may come with leading zeroes and/or leading/trailing spaces. So I may have "0001 " from one database and " 1 " from the other one.

I solved the problem in C# with the following code:

Func<string, string, bool> f = (a,b) => int.Parse(a.Trim()) == int.Parse(b.Trim())

The challenge

This is a really simple challenge, suitable for beginners and any kind of esoteric languages. Given two numbers as strings that may come with leading zeroes and/or leading/trailing spaces, write the shortest code that checks if the two strings represent the same number.

• The inputs need to be two strings or the equivalent in your language (a char array is OK), and they will always represent integer values greater than zero.
• The output must be any two consistent values that represent a truthy value and a falsey value.

Examples

A          B          Result
----------------------------
"0001"     "1    "    true
"1450"     "1450 "    true
"0010001 " " 10001  " true
"0010000"  "  10  "   false
"101023"   "101024"   false


This is , so may the shortest code for each language win!

• ... – user202729 Jan 9 '18 at 11:14
• As least it isn't inspired by your kids this time... – caird coinheringaahing Jan 9 '18 at 15:13
• @cairdcoinheringaahing my own work is my second source of inspiration. I know this is a very simple challenge, but I think these easy challenges are also needed sometimes. I'll try to come up with something more difficult next time. – Charlie Jan 9 '18 at 15:15
• By the way, it seems that my work-inspired challenges are either too easy or too hard... – Charlie Jan 9 '18 at 15:51
• @JonathanAllan no, each input string will represent only one number. There won't be any spaces inbetween the strings. – Charlie Jan 9 '18 at 19:49

# APL (NARS2000), 7 bytes

=⍥⍎


Well, yes, I do know NARS2000 can't compete over Dyalog here since it uses Unicode, but I thought I'd rather show off ⍥ (called Composition in NARS2000, even though it's actually unrelated to function composition), something Dyalog doesn't have as a built-in and I haven't ever seen used here. In Dyalog, it has to be implemented as {(⍵⍵⍺)⍺⍺⍵⍵ ⍵}. What it does is call the right operand monadic function on both the left and right argument, and then call the left operand dyadic function on the results.

Here, the right operand is ⍎ (Execute, i.e. eval) and the left operand is = (Equal To, i.e. check if its arguments are equal).

• Are composition and execute supposed to render as whitespace? – John Dvorak Jan 9 '18 at 23:04
• @JohnDvorak um, no? They're not whitespace, the second char is U+2365 APL FUNCTIONAL SYMBOL CIRCLE DIAERESIS and the third is U+234E APL FUNCTIONAL SYMBOL DOWN TACK JOT. – Erik the Outgolfer Jan 10 '18 at 11:21
• @JohnDvorak Whatever font you're viewing this in may not have symbols for those codepoints. – Οurous Jan 11 '18 at 7:04
• @Οurous I highly suspect that's the case too, but if you're using well-updated software you shouldn't have any problem viewing such chars. – Erik the Outgolfer Jan 11 '18 at 12:22

# R, 37 35 bytes

pryr::f(as.double(x)==as.double(y))


There's probably some cleverer way to coerce strings to numerics but I haven't figured it out yet.

Try it online!

• as.double is shorter. – Giuseppe Jan 9 '18 at 21:48
• @Giuseppe Thanks! – rturnbull Jan 9 '18 at 22:12

# ><>, 2 + 3 = 5 bytes

=n


Try it online!

Uses the -v flag to pass the values into the program. This automatically converts them to numbers, removing the spaces and leading 0s. It then outputs if the two are equal, and exits with an error as it tries to compare an empty stack.

# dc, 9 bytes

[1p]sQ?=Q


Outputs 1 if the numbers are equal, or nothing if unequal. The input numbers are separated by ',', and this gives a warning since data is code in dc. I wasn't sure if space was allowed as delimiter, so I chose one that doesn't stop the program.

Try it online!

# Excel, 8 bytes

=A1-B1=0


Excel does the string to num conversion for us.

(To input as string, prefix values with '.)

## Batch, 89 bytes

@call:c %1
@set e=%errorlevel%
@call:c %2
@if %e%==%errorlevel% echo 1
:c
@exit/b%~1


Prints 1 if the two numbers are the same. Explanation: Batch's numeric processing usually uses leading zeros to indicate an octal number, however exit/b always takes a decimal number. The ~ removes any quotes that would be needed to pass leading or trailing spaces in the parameter.

# Java 8, 58 51 bytes

### 7 bytes thanks to Kevin

b->c->new Long(b.trim()).equals(new Long(c.trim()))


Try it online!

## Explanation

Trims off spaces, casting to Long removes leading zeros, and then returns boolean value if they are equal or not.

• You can save a byte by using currying: b->c-> instead of (b,c)->. In addition, the trailing semi-colon doesn't have to be counted with Java/.NET lambdas. Try it online: 56 bytes – Kevin Cruijssen Jan 10 '18 at 8:36
• 51 bytes by using new Long(...) instead of Long.parseLong(...) – Kevin Cruijssen Jan 10 '18 at 8:40
• Had to check the docs, cause I did not think equals would work, but it does, Long equals checks value not the object – dwana Jan 12 '18 at 15:59
• @dwana Yea, I wish == didn't compare objects or I could have used that and saved a few bytes :P – DevelopingDeveloper Jan 12 '18 at 16:41

# Ruby, 23 bytes

s=->x,y{x.to_i==y.to_i}

• Usage: s.call("0123", "123") – NTCG Jan 11 '18 at 4:56

# Swift, 8079 78 bytes

import Foundation;func r(g:[NSString])->Bool{return g[0].intValue==g[1].intValue}


Try it online!

• Welcome to the site! As Uriel mentioned, this currently counts as a snippet, rather than a function or full program, as it assumes the input is stored in variables. You should change this to be in accordance to these I/O rules. Also, you can check out these tips for golfing in Swift! – caird coinheringaahing Jan 9 '18 at 15:31
• @Uriel Edited my answer. – Tamás Sengel Jan 9 '18 at 15:31

# Pyth, 4 bytes

qFsM


Try it online!

Int-parse each element of the input list with sM(Q), then Fold over equality.

# Wolfram Language, 27 bytes

ToExpression[#1<>"=="<>#2]&


Test cases:

In[1]:= ToExpression[#1 <> "==" <> #2] &["0001", "1"]
Out[1]= True

In[2]:= ToExpression[#1 <> "==" <> #2] &["1450", "1450 "]
Out[2]= True

In[3]:= ToExpression[#1 <> "==" <> #2] &["0010001", " 10001"]
Out[3]= True

In[4]:= ToExpression[#1 <> "==" <> #2] &["0010000", "  10  "]
Out[4]= False

In[5]:= ToExpression[#1 <> "==" <> #2] &["101023", "101024"]
Out[5]= False


# Clean, 52 bytes

import StdEnv
$n=toInt{#c\\c<-n|c>' '} ?n=(==)($n)o$ Try it online! # C++ (gcc), 65 bytes #include<cstdlib> auto a(auto b,auto c){return atoi(b)==atoi(c);}  Try it online! I initially tried used a lambda expression, but auto a=[] is three more characters, and less one more for no trailing semicolon. On the other hand, since atoi is not referenced until the lambda is instantiated, could I delete the #include and put that in the test harness footer instead? # Javascript, 6 bytes Pretty standard stuff, but using Javascript's auto type casting !(a-b)  Or if we don't need it as a function (19 bytes) let f=(a,b)=>!(a-b)  Try it online! https://jsfiddle.net/pgz4ctLy/2/ • Welcome to the site! Note that this is quite similar to the existing Javascript answer... – Charlie Jan 10 '18 at 12:08 • Thanks @charlie, I saw that answer and I didn't believe it met the requirements of "inputs and output" so I posted this answer. Unfortunately being new to the site I wasn't allowed to comment on the other answer so this seemed like the most suitable option and is different enough to stand as it's own. – General Sirhc Jan 10 '18 at 12:13 • There's a lot of ways you can post a valid answer, and one of them is writing a lambda expression. So a valid answer (using your code) would be just (a,b)=>-a==-b. If you use currying, you can write a=>b=>-a==-b. – Charlie Jan 10 '18 at 12:18 • Just to let you know even duplicate answers are fine (although they're rare). – Martin Ender Jan 10 '18 at 12:29 • I have edited my post to be a bit more unique and shorter ;) – General Sirhc Jan 10 '18 at 12:47 ## Mumps, 7 bytes W +X=+Y  In Mumps, all data are strings, the '+' operator evaluates the string to a numeric value. There is no implicit output function, so the 'W' (Write) function provides the output. # AWK, 12 bytes {$0=$1==$2}1


Try it online!

# AWK, 9 bytes

$0=$1==$2  Alternate version: outputs 1 on match, otherwise outputs nothing Try it online! • Oftentimes nothing is not considered a falsey value. If this is run on mutliline input, it's not possible to tell which lines fail. Just my$0.02. Adding {}1 would print the 0 falsey values. – Robert Benson Jan 11 '18 at 18:59

## PHP 5.6+, 16 (42 when callable) bytes

The minimum code that meets the puzzle's requirements (16 bytes):

(int)$a==(int)$b


In callable form (42 bytes):

function f($a,$b){return(int)$a==(int)$b;}


Try it online, with tests

# Explanation

Declare a regular function with a single-character name f with two, otherwise undetermined parameters. It returns the result of comparing both arguments after casting each to integers, which safely removed the padding and whitespace. The code could have been made 2 bytes shorter by converting the function to a closure, but then the closure would not be assigned (which takes another 3 bytes), and therefore not callable.

• Welcome to PPCG! All answers need to be full programs or callable functions (although they may be unnamed function expressions). So the first snippet isn't valid, but the second one is fine. – Martin Ender Jan 10 '18 at 17:04
• @Xano, PHP's type juggling will implicitly convert "numerical looking" strings to numbers, so all you need to do is use the == operator, as long as one is a number. A 32 byte solution using type-coercion would be: function($a,$b){return$a==0+$b;} TIO: tio.run/… – 640KB Jan 24 '19 at 16:19

# Tcl, 45 bytes

proc x a\ b {expr [scan $a %d]==[scan$b %d]}


Try it online!

• Failed outgolf proc x L {expr [join [lmap n $L {scan$n %d}] ==]} on tio.run/… has 50 bytes – sergiol Feb 22 '18 at 15:38

# K (oK), 5 bytes

Solution:

=/.:'


Try it online!

Examples:

=/.:'("0001";"1    ")
1
=/.:'("1450";"1450 ")
1
=/.:'("0010001";" 10001  ")
1
=/.:'("0010000";"  10  ")
0
=/.:'("101023";"101024")
0


Explanation:

Convert each input to an integer, and then check for equality.

=/.:' / the solution
.:' / value (.:) each ('), converts char list to integer
=/    / equality (=) over (/)


# Perl 6, 4 bytes

*==*


Test it

The == operator converts to Numeric which ignores leading and trailing whitespace, and leading 0's get ignored just the same. (0o127 is how you write an octal)

The two * are just there to turn it into a lambda that takes two arguments.

# Implicit, 5 bytes

'ì'ì=


Try it online!

'ì'ì=
'      «read string, push to stack                  »;
ì     «swap type (integer/string) of top of stack  »;
'ì   «do it again for the second integer string   »;
=  «compare for equality                        »;


## C# (32 bytes)

a=>b=>int.Parse(a)==int.Parse(b)


Try it online

as already mentioned in the comments, you can do it shorter than the C# provided in the question. I wrote this thinking I was clever before reading the reply to the comments by the OP. :)

• The whitespace isn't needed at all, and currying can save an additional byte. Try it online! – Dennis Apr 4 '18 at 2:27

R, 55 bytes

V<-strtoi(gsub(" ","",c(A,B),fixed=T),base=9)
V[1]==V[2]


This is my first attempt at codegolf; gave it my best try. Suggestions welcome!

Assumptions:

1. The inputs are given as strings A and B

2. The integers contained are less than 1888888888. Larger values will cause strtoi() to return NA.

# Stratos, 3 bytes

_=_


Both of the _ take an input as a string and convert it to a number, then negate it.

Java converts the input to a number by removing 0s and spaces.

The = takes the results of this and checks for equality

Try it!

# Pyt, 1 byte

=


Explanation

         Implicitly takes two inputs, and casts them to integers/floats if possible.
=        Checks if the two are equal


Try it online!

# FALSE, 36 bytes

[0[^$9>][$32>[48-+10*]?]#%10/]\$!\!=.


Numbers are received from the console, separated by a tab character. True=-1, False=0.