21
\$\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\$
  • 3
    \$\begingroup\$ ... \$\endgroup\$ – user202729 Jan 9 '18 at 11:14
  • 8
    \$\begingroup\$ As least it isn't inspired by your kids this time... \$\endgroup\$ – caird coinheringaahing Jan 9 '18 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 Jan 9 '18 at 15:15
  • \$\begingroup\$ By the way, it seems that my work-inspired challenges are either too easy or too hard... \$\endgroup\$ – Charlie Jan 9 '18 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 Jan 9 '18 at 19:49

56 Answers 56

2
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ Isn't this surprisingly long for Jelly? \$\endgroup\$ – Charlie Jan 9 '18 at 21:16
  • \$\begingroup\$ @Charlie V (eval) is evil, meaning that it can't use the same approach as most other submissions \$\endgroup\$ – caird coinheringaahing Jan 9 '18 at 21:20
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
    \$\begingroup\$ as.double is shorter. \$\endgroup\$ – Giuseppe Jan 9 '18 at 21:48
  • \$\begingroup\$ @Giuseppe Thanks! \$\endgroup\$ – rturnbull Jan 9 '18 at 22:12
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\$

Excel, 8 bytes

=A1-B1=0

Excel does the string to num conversion for us.

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

\$\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\$
  • 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\$ – Kevin Cruijssen Jan 10 '18 at 8:36
  • 1
    \$\begingroup\$ 51 bytes by using new Long(...) instead of Long.parseLong(...) \$\endgroup\$ – Kevin Cruijssen Jan 10 '18 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 Jan 12 '18 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\$ – DevelopingDeveloper Jan 12 '18 at 16:41
2
\$\begingroup\$

Ruby, 23 bytes

s=->x,y{x.to_i==y.to_i}
\$\endgroup\$
  • \$\begingroup\$ Usage: s.call("0123", "123") \$\endgroup\$ – NTCG Jan 11 '18 at 4:56
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
    \$\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\$ – caird coinheringaahing Jan 9 '18 at 15:31
  • 1
    \$\begingroup\$ @Uriel Edited my answer. \$\endgroup\$ – Tamás Sengel Jan 9 '18 at 15:31
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\$
  • 2
    \$\begingroup\$ Welcome to the site! Note that this is quite similar to the existing Javascript answer... \$\endgroup\$ – Charlie Jan 10 '18 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\$ – General Sirhc Jan 10 '18 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 Jan 10 '18 at 12:18
  • 1
    \$\begingroup\$ Just to let you know even duplicate answers are fine (although they're rare). \$\endgroup\$ – Martin Ender Jan 10 '18 at 12:29
  • 1
    \$\begingroup\$ I have edited my post to be a bit more unique and shorter ;) \$\endgroup\$ – General Sirhc Jan 10 '18 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\$

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\$
  • \$\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\$ – Robert Benson Jan 11 '18 at 18:59
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
    \$\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\$ – Martin Ender Jan 10 '18 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 Jan 24 at 16:19
1
\$\begingroup\$

Tcl, 45 bytes

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Failed outgolf proc x L {expr [join [lmap n $L {scan $n %d}] ==]} on tio.run/… has 50 bytes \$\endgroup\$ – sergiol Feb 22 '18 at 15:38
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\$

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\$
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
    \$\begingroup\$ The whitespace isn't needed at all, and currying can save an additional byte. Try it online! \$\endgroup\$ – Dennis Apr 4 '18 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\$
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\$
0
\$\begingroup\$

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!

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

FALSE, 36 bytes

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

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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