# 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

# Javascript, 11 bytes

a=>b=>+a==b


Abusing Javascript's casting rules a bit; +a coerces a into a numeric type.

-6 bytes thanks to Shaggy and Martin Ender♦

Also a cool take by LiefdeWen:

a=>b=>~~a==~~b

• Welcome to PPCG. You can do this in 11 bytes using currying and by only converting one of the inputs to an integer: tio.run/##y0osSyxOLsosKNHNy09J/… Note as well that, unless a function references itself, you don't need to include the variable assignment in your byte count. – Shaggy Jan 9 '18 at 11:06
• Welcome to PPCG! Unnamed functions are fine so you don't need c=, and currying is also fine so you can use a=>b=>... instead of (a,b)=>. Finally, my JavaScript is a bit rusty, but I think something like !(a-b) would also work? – Martin Ender Jan 9 '18 at 11:06
• See the tips for golfing in ES6 (and general JS golfing tips) for more tricks to squeeze bytes out of your solutions. – Shaggy Jan 9 '18 at 12:42
• The cool versiopn is cool but limited in scope, try input '9123456789' and '533522197'. These are string rapresentation of integer values, are well inside the valid range of integers in javascript (but more than 32 bit) – edc65 Jan 9 '18 at 14:39
• Your text no longer matches the code; there's no subtraction. You're coercing a to a numeric type with unary +. – Peter Cordes Jan 10 '18 at 2:01

# 05AB1E, 1 byte

Q


Try it online!

Explanation

Comparison for equality Q will automatically try to evaluate strings as ints before comparing.

• Oh really? And I thought |0+Q was short enough... – Erik the Outgolfer Jan 9 '18 at 19:03

# Operation Flashpoint scripting language, 33 bytes

f={call format(["%1==%2"]+_this)}


Call with:

hint format["%1\n%2\n%3\n%4\n%5",
["0001", "1    "] call f,
["1450", "1450 "] call f,
["0010001 ", " 10001  "] call f,
["0010000", "  10  "] call f,
["101023", "101024"] call f]


Output:

## Alternative version (41 bytes):

f={{t=call _x;r=t==s;s=t}forEach _this;r}


Still 5 bytes shorter than the more straightforward f={t=_this;call(t select 0)==call(t select 1)}

39 bytes:

f={{t=call _x;r=t==s;s=t}count _this;r}


count (which returns the size of an array) works instead of forEach, because you can give it a "lambda" that is used as a condition to count only the array elements that meet that condition. The "condition" used in this case is not a valid condition, but it doesn't matter here because it doesn't cause an error and the return value of the count is not needed.

• I like the variety of situations you take screenshots of your code in. – Οurous Jan 9 '18 at 19:58

# Taxi, 488 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Equal's Corner.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:n 1 l 1 l 1 l.Switch to plan "b" if no one is waiting.'1' is waiting at Writer's Depot.[b]'0' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.


Try it online!

Ungolfed:

Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Equal's Corner.
Pickup a passenger going to Equal's Corner.
Go to Equal's Corner: north 1st left 1st left 1st left.
Switch to plan "b" if no one is waiting.
'1' is waiting at Writer's Depot.
[b]
'0' is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.


Taxi is (relatively) well-suited to this challenge because strings are the only input or output type allowed. The Babelfishery is what converts strings to number (and vice versa) and it handles stripping all the spaces and leading zeroes. It will also handle negative numbers if the - is immediately before the first digit. After that, Equal's Corner checks the two values against each other and Writer's Depot provides the output in string format. Output is 1 for truthy and 0 for falsey.

• Nice one! Just out of curiosity, why is the debug window showing the message error: The boss couldn't find your taxi in the garage. You're fired!? – Charlie Jan 9 '18 at 15:57
• @Charlie Taxi requires you to drive back to the taxi garage when you're done with your route. If you don't bring the car back, you get fired. (You also have to be sure to stop and refuel every now and then or you run out of gas.) In code-golf questions that don't disallow output to STDERR, I generally don't worry about getting fired. You can add this to get rid of the error if you don't want to lose your job: Go to Taxi Garage:n 1 r 1 l 1 r. – Engineer Toast Jan 9 '18 at 16:01
• This answer and its comments are totally surrealistic. I love this community. – Right Leg Jan 11 '18 at 23:10
• @RightLeg My favorite Taxi program I've written took me two weeks and a lot of debugging. You really want a trip, though? Check out Shakespeare. – Engineer Toast Jan 11 '18 at 23:28

# C (gcc), 27 bytes

f(s,t){s=atoi(s)==atoi(t);}


With -O0 (which is the default setting).

Try it online!

# C, 32 bytes

f(s,t){return atoi(s)==atoi(t);}


Try it online!

• @Charlie In C, strings are arrays of char, and when you pass an array to a function you actually just pass the pointer to the first element of the array. Here, the pointers to the char arrays are implicitly converted to integers when passed to the function, and the integers are converted back to pointers when calling atoi. – Steadybox Jan 9 '18 at 10:38
• which could blow up horribly on a platform where pointers are wider than ints ... just saying, of course it's fine for site standards here :) – Felix Palmen Jan 9 '18 at 12:33
• If you want to use ridiculous crap like s=foo; instead of return foo; you need to label this as "x86 gcc with optimization disabled", not just "C", because this code doesn't return a value except as an implementation artefact. – Peter Cordes Jan 9 '18 at 13:18
• I went looking to see if there were any architectures where s=retval; instead of return retval; actually broke. It looks like gcc's internal logic (with -O0 only) actually treats the last expression as the return value, maybe the same way that a GNU C statement-expression works. (But it does require s=). On ARM32, it calculates the == result in r3, and then uses an extra mov r0, r3 to make that the return value! So it's not an x86-specific hack, it's a gcc -O0 hack that gcc seems to go out of its way to support. – Peter Cordes Jan 10 '18 at 1:50
• @KenY-N You're missing the entire point of c code golf. It's about finding those specific hacky edge cases where you can input the minimum amount of code and get the results you want, not providing a portable experience. – user77406 Jan 10 '18 at 18:47

# J, 4 bytes

=&do


Compare = after & evaluating do. Can also be =&". Try it online!

• Interestingly enough this will work for both negatives as other languages understand them (e.g. -10) and negatives as J understands them (e.g. _10) due to the way monadic - works. – cole Jan 9 '18 at 19:17

## Retina, 11 bytes

.+
$* D ¶$


Try it online!

Input is linefeed separated, but the test suite uses comma separation for convenience. Prints 1 for equality and 0 for inequality.

### Explanation

.+
$*  Convert each line to unary. This ignores leading zeros and spaces. D  Deduplicate: clear the second line if both are the same. ¶$


Check that the string now ends in a linefeed.

# Python 3, 25 bytes

lambda a,b:int(a)==int(b)


Try it online!

# Brain-Flak, 22 bytes

(([{}]{})[{(){}}](){})


Try it online!

Saved 4 bytes thanks to Jo King.

# Triangularity, 17 bytes

..)..
.Ii).
@Ii=.


Try it online!

Triangularity is, for once, competitive!

### How it works

Triangularity requires the code to have a triangular distribution of the dots. That is, the length of each row must be equal the number of rows multiplied by 2 and decremented, and each row must have (on each side) a number of dots equal to its position in the program (the bottom row is row 0, the one above it is row 1 and so forth). Keeping this in mind, let's analyse how the code works:

..).. || Push a 0 onto the stack.
.Ii   || Get the 0th input and cast it to an integer.
). || Push another 0 onto the stack.
@I    || Increment the ToS => 1. Get the first input.
i=. || Then cast it to an integer and compare their equality.


## Alice, 7 bytes

X/n
o@i


Try it online!

Any non-digit separator works. Prints 1 for equality and 0 otherwise.

### Explanation

X   XOR, does nothing.
/   Switch to Ordinal mode.
i   Read all input as a string.
/   Switch to Cardinal mode.
X   XOR. Implicitly finds all integers in the string and pushes them separately
onto the stack. The XOR gives 0 if the values are identical.
n   Logical NOT. Gives 1 for equal inputs and 9 otherwise.
/   Switch to Ordinal.
o   Print the 0 or 1 as a string.
/   Switch to Cardinal.
@   Terminate the program.


# Japt, 3 bytes

¥Vn


Try it

Converts the second input to an integer and compares equality with the first.

# APL (Dyalog), 4 bytes

3 bytes saved thanks to @Adám

=/⍎¨


Try it online!

# jq, 24 characters

map(tonumber)|.[0]==.[1]


The 2 strings are passed as items of an array.

Sample run:

bash-4.4$jq 'map(tonumber)|.[0]==.[1]' <<< '["0010001 ", " 10001 "]' true bash-4.4$ jq 'map(tonumber)|.[0]==.[1]' <<< '["0010000", "  10  "]'
false


# Husk, 3 bytes

¤=r


Try it online!

### Explanation

¤    -- combine both arguments of ..
=   -- .. equality ..

• If you take input as a two-element list, Ër works too. – Zgarb Jan 10 '18 at 11:56

# PowerShell, 20 bytes

param($a,$b)+$a-eq$b


Similar to the JavaScript answer, just longer because PowerShell doesn't have currying. Uses + to cast the first string to integer, and then the -equals automatically casts the second string to integer. Output is True/False.

Try it online!

# Jelly, 8 bytes

t€⁶V€€ḌE


Try it online! or see the test suite

35 answers, and no Jelly submission? Takes the argument as a list (["0001", "1 "] for the first example)

## How it works

t€⁶V€€ḌE - Main link. Argument: list       e.g.    ["0001", "1    "]
€       - For €ach element...                     ["0001", "1"]
t        -   trim from both sides...
⁶      -   spaces
€   - For €ach element...
V€    -   evaluate €ach character               [[0, 0, 0, 1], [1]]
Ḍ  - Convert from digits                     [1, 1]
E - Are they equal?                         1

• Isn't this surprisingly long for Jelly? – Charlie Jan 9 '18 at 21:16
• @Charlie V (eval) is evil, meaning that it can't use the same approach as most other submissions – caird coinheringaahing Jan 9 '18 at 21:20

# PowerShell, 19 bytes

$args-join'-eq'|iex  Try it online! -join the argument array ($args) with the string representation of the comparison operator (-eq) then evaluate the expression with Invoke-Expression (iex).

• Interesting. I wonder how you get by without needing to cast to integer, whereas mine breaks if I remove the + since it's doing string equality checking. – AdmBorkBork Jan 12 '18 at 13:40
• @AdmBorkBork because I'm essentially generating PowerShell code and then executing it, and since leading zeroes and leading/trailing spaces don't matter for the interpreter, it "just works". If the 2 numbers are 00009  and 077  then the resultant code is 00009 -eq077 , a perfectly valid piece of code. You're dealing directly with the string at runtime, so you must cast it first so the operation is done on a numeric. – briantist Jan 12 '18 at 20:18
• Right, yes, that makes sense. Thanks for the explanation. – AdmBorkBork Jan 12 '18 at 21:00

# Q (Kdb+), 13 bytes

• I would say that this should be written as a lambda including the curly braces, i.e. {=/["J"$(x;y)]} for 15 bytes... Although for 8 bytes you could have this: (~/)"J"$ if you are just using the REPL and passing the inputs as a list of strings... or {(~/)"J"$x} for 11 as a function. – streetster Jan 13 '18 at 11:05 # T-SQL, 35 bytes Per our standards, data is input via pre-existing table t with varchar fields a and b.  SELECT IIF(ABS(a)=ABS(b),1,0)FROM t  Returns 1 if they match, 0 if they don't. A few of SQL's mathematical functions (including ABS, FLOOR and CEILING) will do an implicit conversion to numeric if given string parameters, this is shorter than an explicit CAST(a AS INT) or CONVERT(INT,b), and works in this case since we know the input values are always positive. IIF is specific to MS SQL 2012 and above, so no guarantee about other implementations. # Excel VBA, 27 16 Bytes -9 Thanks to @Nayrb and @TaylorScott [C1]=[A1]-[B1]=0  Where you input the values on the Cells with 'string. Where x and y are the input Strings and z is a Boolean output. If CInt(x)=CInt(y) Then z=1 Using CInt • Why not: z=x-y=0? – Nayrb Jan 9 '18 at 15:44 • Unfortunately this solution is invalid as it does not take input and rather relies on having predefined values (which has been deemed against the community's rules) and outputing to a variable (which is also against community rules) – Taylor Scott Jan 11 '18 at 14:36 • As for a valid solution perhaps a vbe immediate window function such as ?[Int(A1)=Int(B1)] that takes input from the ranges A1 and B1 and outputs to the VBE immediate window – Taylor Scott Jan 11 '18 at 14:38 # R, 28 27 bytes !diff(as.double(scan(,'')))  Reads numbers as strings, converts them to doubles and checks if their difference is not zero. Try it online! −1 byte thanks to Giuseppe • Just "" is sufficient – Giuseppe Apr 4 '18 at 1:44 # Lua, 20 bytes print(...-arg[2]==0)  Try it online! # Haskell, 20 bytes -11 bytes thanks to Laikoni. -2 bytes thanks to Zgarb. a#b=0+read a==read b  Try it online! • @Laikoni It's even better to not bind read: a#b=0+read a==read b – Zgarb Jan 9 '18 at 10:58 # Gema, 21 characters *\n*=@cmpn{*;*;0;1;0}  No boolean in Gema. As the @get-switch{}/@set-switch{} functions use 0 and 1 to represent switch statuses, also used 0 and 1. The 2 strings are passed on separate input lines. Sample run: bash-4.4$ gema '*\n*=@cmpn{*;*;0;1;0}' <<< $'0010001\n10001 ' 1 bash-4.4$ gema '*\n*=@cmpn{*;*;0;1;0}' <<< $'0010000\n 10 ' 0  # Perl 5, 9 + 1 (-p) = 10 bytes $_=$_==<>  try it online # Stacked, 8 bytes [#~\#~=]  Try it online! ## Explanation [#~\#~=] anonymous function #~ eval TOS \ swap top two #~ eval TOS = push equality of top two  # Attache, 11 bytes Same@Map&:N  Try it online! This takes an array of strings, such as V["0001", "1 "]. Simply stated, Map&:N is a function that maps N over its argument, and Same checks that the array contains only equal members. (Fun fact: this function works for more than 2 string arguments.) # SNOBOL4 (CSNOBOL4), 42 bytes  OUTPUT =EQ(EVAL(INPUT),EVAL(INPUT)) 1 END  Try it online! Outputs 1 for truthy, nothing for falsey. Since (space) is the concatenation operator in SNOBOL, EVALing a number with leading/trailing spaces yields the number itself, and it also neatly takes care of any leading zeroes. EQ tests for numerical equality, conditionally setting OUTPUT to 1 on Success. # Sinclair ZX81/Timex TS1000/1500 BASIC, ~29 tokenized BASIC bytes New solution thanks to Neil (thanks for the tip).  1 INPUT A$
2 INPUT B$3 PRINT VAL A$=VAL B$ This solution requires user input, so enter in two strings with white spaces and/or leading zeros, or enter two strings of non-equal numeric value; 0 is false and 1 is true once line three has compared the value of each string entered. ### Old solution: Sinclair ZX81/Timex TS1000/1500 BASIC, ~46 tokenized BASIC bytes  1 LET A$=" 001 "
2 LET B$="1" 3 PRINT (VAL A$=VAL B$)  The actual check is done in line three, which is only ~16 tokenized BASIC bytes; so entering each test case pair using direct mode will save ~30 bytes from the listing. Note that this byte count does not include the var stack. • Shouldn't you use INPUT A$ and INPUT B\$? Also I don't think you need the ()s. – Neil Jan 9 '18 at 16:19