20
\$\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

23
\$\begingroup\$

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
\$\endgroup\$
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Shaggy Jan 9 '18 at 11:06
  • 2
    \$\begingroup\$ 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? \$\endgroup\$ – Martin Ender Jan 9 '18 at 11:06
  • 1
    \$\begingroup\$ See the tips for golfing in ES6 (and general JS golfing tips) for more tricks to squeeze bytes out of your solutions. \$\endgroup\$ – Shaggy Jan 9 '18 at 12:42
  • 1
    \$\begingroup\$ 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) \$\endgroup\$ – edc65 Jan 9 '18 at 14:39
  • 1
    \$\begingroup\$ Your text no longer matches the code; there's no subtraction. You're coercing a to a numeric type with unary +. \$\endgroup\$ – Peter Cordes Jan 10 '18 at 2:01
18
\$\begingroup\$

05AB1E, 1 byte

Q

Try it online!

Explanation

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

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

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.

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

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ 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!? \$\endgroup\$ – Charlie Jan 9 '18 at 15:57
  • 6
    \$\begingroup\$ @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. \$\endgroup\$ – Engineer Toast Jan 9 '18 at 16:01
  • \$\begingroup\$ This answer and its comments are totally surrealistic. I love this community. \$\endgroup\$ – Right Leg Jan 11 '18 at 23:10
  • \$\begingroup\$ @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. \$\endgroup\$ – Engineer Toast Jan 11 '18 at 23:28
10
\$\begingroup\$

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!

\$\endgroup\$
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ – Steadybox Jan 9 '18 at 10:38
  • 1
    \$\begingroup\$ 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 :) \$\endgroup\$ – Felix Palmen Jan 9 '18 at 12:33
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Peter Cordes Jan 9 '18 at 13:18
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Peter Cordes Jan 10 '18 at 1:50
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ – user77406 Jan 10 '18 at 18:47
8
\$\begingroup\$

J, 4 bytes

=&do

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – cole Jan 9 '18 at 19:17
6
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

Brain-Flak, 22 bytes

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

Try it online!

Saved 4 bytes thanks to Jo King.

\$\endgroup\$
3
\$\begingroup\$

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

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

Japt, 3 bytes

¥Vn

Try it

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

\$\endgroup\$
3
\$\begingroup\$

APL (Dyalog), 4 bytes

3 bytes saved thanks to @Adám

=/⍎¨

Try it online!

\$\endgroup\$
  • \$\begingroup\$ =/⍎¨ \$\endgroup\$ – Adám Jan 9 '18 at 10:46
3
\$\begingroup\$

Python 3, 25 bytes

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

Try it online!

\$\endgroup\$
3
\$\begingroup\$

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

Try it online! (All test cases)

\$\endgroup\$
3
\$\begingroup\$

Husk, 3 bytes

¤=r

Try it online!

Explanation

¤    -- combine both arguments of ..
 =   -- .. equality ..
  r  -- .. with read
\$\endgroup\$
  • 1
    \$\begingroup\$ If you take input as a two-element list, Ër works too. \$\endgroup\$ – Zgarb Jan 10 '18 at 11:56
3
\$\begingroup\$

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!

\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – AdmBorkBork Jan 12 '18 at 13:40
  • \$\begingroup\$ @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. \$\endgroup\$ – briantist Jan 12 '18 at 20:18
  • \$\begingroup\$ Right, yes, that makes sense. Thanks for the explanation. \$\endgroup\$ – AdmBorkBork Jan 12 '18 at 21:00
3
\$\begingroup\$

Q (Kdb+), 13 bytes

=/["J"$(x;y)]

Explanation

(x;y) : a list of the two inputs.

"J"$ : casting each input to a long (7j) type from string (10c), which can correctly interpret
white space and leading 0s.

=/ : checks equality over elements in a list (each subsequent pair).
As there is only one pair, returns single boolian 0b/1b.

\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! Usually, a link to an online interpreter/compiler is appreciated, and if not obvious, an explanation as well. \$\endgroup\$ – FantaC Jan 10 '18 at 19:40
  • \$\begingroup\$ Thanks! Explanation added there. I doubt there is an online interpreter for q, I did a quick look and couldn't find one. \$\endgroup\$ – Sidney Jan 11 '18 at 15:15
  • \$\begingroup\$ 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. \$\endgroup\$ – streetster Jan 13 '18 at 11:05
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
  • 1
    \$\begingroup\$ Why not: z=x-y=0? \$\endgroup\$ – Nayrb Jan 9 '18 at 15:44
  • \$\begingroup\$ 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) \$\endgroup\$ – Taylor Scott Jan 11 '18 at 14:36
  • \$\begingroup\$ 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 \$\endgroup\$ – Taylor Scott Jan 11 '18 at 14:38
3
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ Just "" is sufficient \$\endgroup\$ – Giuseppe Apr 4 '18 at 1:44
2
\$\begingroup\$

Lua, 20 bytes

print(...-arg[2]==0)

Try it online!

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

Haskell, 20 bytes

-11 bytes thanks to Laikoni. -2 bytes thanks to Zgarb.

a#b=0+read a==read b

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ @Laikoni It's even better to not bind read: a#b=0+read a==read b \$\endgroup\$ – Zgarb Jan 9 '18 at 10:58
2
\$\begingroup\$

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

Perl 5, 9 + 1 (-p) = 10 bytes

$_=$_==<>

try it online

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

Stacked, 8 bytes

[#~\#~=]

Try it online!

Explanation

[#~\#~=]   anonymous function
 #~        eval TOS
   \       swap top two
    #~     eval TOS
      =    push equality of top two
\$\endgroup\$
2
\$\begingroup\$

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

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

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.

\$\endgroup\$
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\$
  • 1
    \$\begingroup\$ Shouldn't you use INPUT A$ and INPUT B$? Also I don't think you need the ()s. \$\endgroup\$ – Neil Jan 9 '18 at 16:19
  • \$\begingroup\$ Yes, I could use that also - I just wanted a proof of concept \$\endgroup\$ – Shaun Bebbers Jan 9 '18 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\$
  • \$\begingroup\$ Are composition and execute supposed to render as whitespace? \$\endgroup\$ – John Dvorak Jan 9 '18 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\$ – Erik the Outgolfer Jan 10 '18 at 11:21
  • \$\begingroup\$ @JohnDvorak Whatever font you're viewing this in may not have symbols for those codepoints. \$\endgroup\$ – Οurous Jan 11 '18 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\$ – Erik the Outgolfer Jan 11 '18 at 12:22

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.