25
\$\begingroup\$

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!

\$\endgroup\$
10
  • 3
    \$\begingroup\$ ... \$\endgroup\$
    – DELETE_ME
    Commented Jan 9, 2018 at 11:14
  • 9
    \$\begingroup\$ As least it isn't inspired by your kids this time... \$\endgroup\$ Commented Jan 9, 2018 at 15:13
  • 2
    \$\begingroup\$ @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. \$\endgroup\$
    – Charlie
    Commented Jan 9, 2018 at 15:15
  • \$\begingroup\$ By the way, it seems that my work-inspired challenges are either too easy or too hard... \$\endgroup\$
    – Charlie
    Commented Jan 9, 2018 at 15:51
  • \$\begingroup\$ @JonathanAllan no, each input string will represent only one number. There won't be any spaces inbetween the strings. \$\endgroup\$
    – Charlie
    Commented Jan 9, 2018 at 19:49

64 Answers 64

2
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Shouldn't you use INPUT A$ and INPUT B$? Also I don't think you need the ()s. \$\endgroup\$
    – Neil
    Commented Jan 9, 2018 at 16:19
  • \$\begingroup\$ Yes, I could use that also - I just wanted a proof of concept \$\endgroup\$ Commented Jan 9, 2018 at 18:42
2
\$\begingroup\$

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

\$\endgroup\$
4
  • \$\begingroup\$ Are composition and execute supposed to render as whitespace? \$\endgroup\$ Commented Jan 9, 2018 at 23:04
  • \$\begingroup\$ @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. \$\endgroup\$ Commented Jan 10, 2018 at 11:21
  • \$\begingroup\$ @JohnDvorak Whatever font you're viewing this in may not have symbols for those codepoints. \$\endgroup\$
    – Οurous
    Commented Jan 11, 2018 at 7:04
  • \$\begingroup\$ @Ο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. \$\endgroup\$ Commented Jan 11, 2018 at 12:22
2
\$\begingroup\$

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!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ as.double is shorter. \$\endgroup\$
    – Giuseppe
    Commented Jan 9, 2018 at 21:48
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ Commented Jan 10, 2018 at 8:36
  • 1
    \$\begingroup\$ 51 bytes by using new Long(...) instead of Long.parseLong(...) \$\endgroup\$ Commented Jan 10, 2018 at 8:40
  • 1
    \$\begingroup\$ Had to check the docs, cause I did not think equals would work, but it does, Long equals checks value not the object \$\endgroup\$
    – dwana
    Commented Jan 12, 2018 at 15:59
  • \$\begingroup\$ @dwana Yea, I wish == didn't compare objects or I could have used that and saved a few bytes :P \$\endgroup\$ Commented Jan 12, 2018 at 16:41
2
\$\begingroup\$

Ruby, 23 bytes

s=->x,y{x.to_i==y.to_i}
\$\endgroup\$
1
  • \$\begingroup\$ Usage: s.call("0123", "123") \$\endgroup\$
    – NTCG
    Commented Jan 11, 2018 at 4:56
2
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jan 11, 2018 at 18:59
2
\$\begingroup\$

Tcl, 45 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Failed outgolf proc x L {expr [join [lmap n $L {scan $n %d}] ==]} on tio.run/… has 50 bytes \$\endgroup\$
    – sergiol
    Commented Feb 22, 2018 at 15:38
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Swift, 80 79 78 bytes

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

Try it online!

\$\endgroup\$
2
  • 2
    \$\begingroup\$ 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! \$\endgroup\$ Commented Jan 9, 2018 at 15:31
  • 1
    \$\begingroup\$ @Uriel Edited my answer. \$\endgroup\$ Commented Jan 9, 2018 at 15:31
2
\$\begingroup\$

Julia 1.0, 26 bytes

~x=parse(Int,x);a%b=~a==~b

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Julia 1.0, 30 bytes

a%b=eval(Meta.parse("$a==$b"))

Try it online!

Some meta programming fun, not the shortest solution though

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

Pyth, 4 bytes

qFsM

Try it online!

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

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

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

Clean, 52 bytes

import StdEnv
$n=toInt{#c\\c<-n|c>' '}
?n=(==)($n)o$

Try it online!

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

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?

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

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/

\$\endgroup\$
5
  • 2
    \$\begingroup\$ Welcome to the site! Note that this is quite similar to the existing Javascript answer... \$\endgroup\$
    – Charlie
    Commented Jan 10, 2018 at 12:08
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Jan 10, 2018 at 12:13
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Charlie
    Commented Jan 10, 2018 at 12:18
  • 1
    \$\begingroup\$ Just to let you know even duplicate answers are fine (although they're rare). \$\endgroup\$ Commented Jan 10, 2018 at 12:29
  • 1
    \$\begingroup\$ I have edited my post to be a bit more unique and shorter ;) \$\endgroup\$ Commented Jan 10, 2018 at 12:47
1
\$\begingroup\$

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.

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

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.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Commented Jan 10, 2018 at 17:04
  • \$\begingroup\$ @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/… \$\endgroup\$
    – 640KB
    Commented Jan 24, 2019 at 16:19
1
\$\begingroup\$

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 (/)
\$\endgroup\$
1
\$\begingroup\$

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                        »;
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ The whitespace isn't needed at all, and currying can save an additional byte. Try it online! \$\endgroup\$
    – Dennis
    Commented Apr 4, 2018 at 2:27
1
\$\begingroup\$

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.

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

Vyxal, 3 bytes

"⌊≈

Try it Online!

Explained

"⌊≈
"   # pair both inputs into list
 ⌊  # floor
  ≈ # all items equal?
\$\endgroup\$
1
\$\begingroup\$

nroff, 51 bytes

1 and 0 for truthy and falsey. Wish type convertion were available. .nr X \\$1=\\$2 did not work for some input.

.de F
.nr X \\$1
.nr Y \\$2
.nr X \\nX=\\nY
\\nX
..

Attempt This Online!

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

J-uby, 9 bytes

:*&Z|+:==

Attempt This Online!

Explanation

:* & Z |       # Map with to_i (Z), then
         +:==  # Compare

I think this would be 7 bytes with J-uby’s ** operator:

Z**+:==

…but it’s broken or removed in the current version.

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

Thunno 2, 2 bytes

Nạ

Attempt This Online!

The "cast to integer" built-in (N) handles leading/trailing spaces and leading zeros. Then, we can just check equality with .

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

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!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.