41
\$\begingroup\$

Imagine travelling to a point lying A miles away horizontally and B miles away vertically from your current position. Or in other words, travelling from (0, 0) to point (a, b). How far would you need to end up travelling? This seems like a straightforward question, but the answer depends on who you ask. If you're a crow, and you can travel as the crow flies, the distance travelled is just the Euclidean distance to (a, b). This is

sqrt(a^2 + b^2)

But if you're just a boring human, you don't really want to walk that far, so you'll need to take a taxi. Most taxis wont drive in a straight line towards your destination because they generally try to stay on the roads. So the real distance you'll end up travelling is the sum of the vertical distance and the horizontal distance. Or the formula is:

abs(a) + abs(b)

This is called the Taxicab Distance. This picture nicely demonstrates the difference between the two:

enter image description here

To travel to (6, 6), a crow can just fly on the green line, and this gives a distance of 6 * sqrt(2) or roughly 8.49. A taxicab can take the red, blue or yellow paths, but they will all take 12.

This leads to the real question I'm asking. If a crow and a taxicab both leave from point (0, 0), and travel to point (a, b), how much longer is the taxicab's path? Or, in more math jargon,

Given a two dimensional vector, determine the difference between the norm2 of the vector, and the norm1 of the vector.

You must write the shortest possible program or function to answer this question. You may choose to take 'a' and 'b' as two separate inputs, or as a two item tuple. You can take input and output in any reasonable format. If the difference is a non integer, you must be accurate to at least two decimal places.

You can always assume that 'a' and 'b' will be integers, and that they won't both be 0. (Though it is possible that either one of them will be zero)

As usual, standard loopholes apply and try to make your program as short as possible, counted in bytes.

I will upvote any answer that posts an explanation of how the code works, and demonstrates any cool tricks used to save bytes.

Here are some examples for you to test your code on:

#input    #output
3, 4      2
-3, 4     2
-3, -4    2
6, 6      3.51
42, 0     0
10, 10    5.86
3, 3      1.76

Have fun golfing! :)

\$\endgroup\$
10
  • 10
    \$\begingroup\$ can we take input as complex number? \$\endgroup\$
    – Uriel
    Jul 8, 2017 at 20:45
  • \$\begingroup\$ I think the testcase for 10,10 needs to be 5.86, since it comes out to 5.85786... and you rounded the one below it. \$\endgroup\$ Jul 9, 2017 at 5:31
  • 5
    \$\begingroup\$ I first read the title as The Cow vs The Taxicab and was hoping to find something involving collision physics... \$\endgroup\$
    – MooseBoys
    Jul 10, 2017 at 6:02
  • \$\begingroup\$ May we give negative results? \$\endgroup\$
    – Adám
    Jul 10, 2017 at 22:11
  • \$\begingroup\$ @Adám No. (Since conceptually, you're returning a distance, which is always positive) \$\endgroup\$
    – DJMcMayhem
    Jul 10, 2017 at 22:13

41 Answers 41

111
\$\begingroup\$

Taxi, 7394 3773 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:n.[a]Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Multiplication Station.1 is waiting at Starchild Numerology.Go to Starchild Numerology:s 2 l 2 r.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 4 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to The Underground.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Multiplication Station.Go to The Underground:n 2 r 2 r.Switch to plan "b" if no one is waiting.Pickup a passenger going to Charboil Grill.Go to Charboil Grill:s 2 r 1 l 1 l 2 r.-1 is waiting at Starchild Numerology.Go to Starchild Numerology:e 2 r.Pickup a passenger going to Multiplication Station.Go to The Underground:w 1 r 2 r 1 r 2 l.[b]Go to Multiplication Station:s 1 l 1 r.Go to Tom's Trims:s 1 r 3 r.Switch to plan "c" if no one is waiting.Switch to plan "a".[c]Go to Multiplication Station:s 1 l 3 l.Pickup a passenger going to Cyclone.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 r 2 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Cyclone.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Multiplication Station.-1 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 3 l.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:w 1 r 2 r 1 r 4 l.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:s 1 r 2 l 1 l 1 r 1 r.Go to Cyclone:s 1 l 1 l 1 l 1 r.Pickup a passenger going to Cyclone.[d]Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to Addition Alley.Go to Cyclone:s 1 r 2 l 2 r.Switch to plan "e" if no one is waiting.Switch to plan "d".[e]Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Cyclone.99 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 3 l.Pickup a passenger going to The Underground.Go to Cyclone:e 1 l 2 r.Pickup a passenger going to Trunkers.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 r.Go to Trunkers:s 1 l.[f]Pickup a passenger going to Cyclone.Go to Cyclone:w 2 r.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Trunkers.Go to Trunkers:s 1 l.Go to Sunny Skies Park:w 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l.Pickup a passenger going to Divide and Conquer.Go to Zoom Zoom:n.Go to Divide and Conquer:w 1 l 2 r 1 r.Pickup a passenger going to Addition Alley.Go to Cyclone:e 1 l 1 l 2 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Divide and Conquer.2 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 3 l 2 r.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:w 1 r 2 r 1 r 2 l 3 l.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:e 1 l 1 l 2 l 1 l.Go to The Underground:s 1 l 1 r 2 l.Switch to plan "g" if no one is waiting.Pickup a passenger going to The Underground.Go to Trunkers:s 2 r 1 l.Switch to plan "f".[g]Go to Rob's Rest:n 3 l 2 l 1 l 2 r 1 r.Pickup a passenger going to What's The Difference.Go to Sunny Skies Park:s 1 l 1 l.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 3 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

Try it online!

Engineer Toast, a much more experienced Taxi golfer, decided to take some time (probably a lot less than I did) and golf down my Taxi program by basically rewriting it. You can find my old answer body and links to my old TIOs in the edit history.

Engineer Toast's ungolfed square root algorithm: Try it online!

Ungolfed, with explanations:

[ Crow vs. Taxi ]


[ GET THE NEGATIVE ABSOLUTE VALUES OF BOTH STDINS ]

[Move the stdin values to Tom's Trims b/c:]
[1) Stdin doesn't count as a passenger waiting]
[2) Checking for no one waiting is shorter that keeping tracker of a count for just 2 iterations OR repeating all the code over again]
Go to Post Office:w 1 l 1 r 1 l.
Pickup a passenger going to Tom's Trims.
Pickup a passenger going to Tom's Trims.
Go to Tom's Trims:n.

[a]
[Clone the first waiting value]
[If we've already picked up both, move to the next process]
[Switch to plan "c" if no one is waiting.]
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:s 1 l 1 r.
Pickup a passenger going to Cyclone.
Go to Cyclone:n 1 l 1 l 2 r.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Multiplication Station.

[Add one to the value]
1 is waiting at Starchild Numerology.
Go to Starchild Numerology:s 2 l 2 r.
Pickup a passenger going to Cyclone.
Go to Cyclone:w 1 r 4 l.
Pickup a passenger going to Addition Alley.
Go to Addition Alley:n 2 r 1 r.
Pickup a passenger going to The Underground.

[Pick up a clone of that one to feed into Multiplication Station]
Go to Cyclone:n 1 l 1 l.
Pickup a passenger going to Multiplication Station.

[Subtract one and see if that's more than zero]
Go to The Underground:n 2 r 2 r.
Switch to plan "b" if no one is waiting.

[It was more than zero so we make it negative]
[First, though, get rid of the pesky result from The Underground]
Pickup a passenger going to Charboil Grill.
Go to Charboil Grill:s 2 r 1 l 1 l 2 r.
-1 is waiting at Starchild Numerology.
Go to Starchild Numerology:e 2 r.
Pickup a passenger going to Multiplication Station.
Go to The Underground:w 1 r 2 r 1 r 2 l.

[b]
[Make sure it's a negative value and leave it at Multiplication Station]
[Either it was already negative OR we now have -1 as a passenger]
Go to Multiplication Station:s 1 l 1 r.

[Get the next stdin unless we've already gotten them both]
Go to Tom's Trims:s 1 r 3 r.
Switch to plan "c" if no one is waiting.
Switch to plan "a".


[ ADD THE TWO NEGATIVES AND INVERT TO GET THE TAXI DISTANCE]

[c]
[Pickup the two negative absolute values and clone them]
Go to Multiplication Station:s 1 l 3 l.
Pickup a passenger going to Cyclone.
Pickup a passenger going to Cyclone.
Go to Cyclone:s 1 r 2 l 2 r.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Cyclone.
Pickup a passenger going to Addition Alley.

[Add the two clones values to get the negative Taxi distance]
Go to Addition Alley:n 2 r 1 r.
Pickup a passenger going to Multiplication Station.

[Invert to get the Taxi distance and store it at Rob's Rest]
-1 is waiting at Starchild Numerology.
Go to Starchild Numerology:n 1 l 1 l 1 l 3 l.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station:w 1 r 2 r 1 r 4 l.
Pickup a passenger going to Rob's Rest.
Go to Rob's Rest:s 1 r 2 l 1 l 1 r 1 r.


[ FIND THE CROW DISTANCE ]
[Uses the Babylonian method: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method ]

[Square and Sum the cloned values]
Go to Cyclone:s 1 l 1 l 1 l 1 r.
Pickup a passenger going to Cyclone.
[d]
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station:s 1 l 2 r 4 l.
Pickup a passenger going to Addition Alley.
Go to Cyclone:s 1 r 2 l 2 r.
Switch to plan "e" if no one is waiting.
Switch to plan "d".
[e]
Go to Addition Alley:n 2 r 1 r.
Pickup a passenger going to Cyclone.

[Pickup our cycle counter]
[It's cheaper to do this than to check each iteration's value as equal to the last]
[Taxi can only handle integers up to 2^31-1 so 99 iterations is sufficient.]
99 is waiting at Starchild Numerology.
Go to Starchild Numerology:n 1 l 1 l 1 l 3 l.
Pickup a passenger going to The Underground.

[Duplicate stdin to be stored as S at Trunkers and as x0 at Sunny Skies Park]
[a & b are always integers so Trunkers won't hurt S and it's close with a short name so it's good for golfing]
Go to Cyclone:e 1 l 2 r.
Pickup a passenger going to Trunkers.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park:n 1 r.
Go to Trunkers:s 1 l.

[ This is our starting position for square root:           ]
[  • x at Sunny Skies Park                                 ]
[  • S at Trunkers                                         ]
[  • Taxi at Trunkers                                      ]
[  • The iterator as a passenger going to The Underground  ]

[f]

[Duplicate S so we don't lose it]
Pickup a passenger going to Cyclone.
Go to Cyclone:w 2 r.
Pickup a passenger going to Divide and Conquer.
Pickup a passenger going to Trunkers.
Go to Trunkers:s 1 l.

[Diplicate x for division and addition]
Go to Sunny Skies Park:w 1 r.
Pickup a passenger going to Cyclone.
Go to Cyclone:n 1 l.
Pickup a passenger going to Divide and Conquer.

[Gas will be super important in this loop]
Go to Zoom Zoom:n.

[Perform (x + S/x)/2]
[(/2) turns out to be a few bytes shorter than (*.5), mostly due to place names]
Go to Divide and Conquer:w 1 l 2 r 1 r.
Pickup a passenger going to Addition Alley.
Go to Cyclone:e 1 l 1 l 2 l.
Pickup a passenger going to Addition Alley.
Go to Addition Alley:n 2 r 1 r.
Pickup a passenger going to Divide and Conquer.
2 is waiting at Starchild Numerology.
Go to Starchild Numerology:n 1 l 1 l 3 l 2 r.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer:w 1 r 2 r 1 r 2 l 3 l.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park:e 1 l 1 l 2 l 1 l.
[Now we have the next iteration of x]

[Check the iterator]
Go to The Underground:s 1 l 1 r 2 l.
Switch to plan "g" if no one is waiting.
Pickup a passenger going to The Underground.

[Reset the loop]
Go to Trunkers:s 2 r 1 l.
Switch to plan "f".


[ ADD THE NEGATIVE SUM TO THE SQUARE ROOT TO GET THE NEGATIVE DIFFERENCE ]

[g]
Go to Rob's Rest:n 3 l 2 l 1 l 2 r 1 r.
Pickup a passenger going to What's The Difference.
Go to Sunny Skies Park:s 1 l 1 l.
Pickup a passenger going to What's The Difference.
Go to What's The Difference:n 1 r 1 l.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:e 3 r.
Pickup a passenger going to Post Office.
Go to Post Office:n 1 l 1 r.
\$\endgroup\$
14
  • 1
    \$\begingroup\$ This is insane... \$\endgroup\$
    – Gryphon
    Jul 9, 2017 at 16:51
  • 2
    \$\begingroup\$ @Gryphon the insane thing is I am 100% sure I can remove like two thousand bytes once I revisit my logic while I'm not half asleep \$\endgroup\$
    – Stephen
    Jul 9, 2017 at 17:05
  • 4
    \$\begingroup\$ 4 hours is deserving of the +1 in itself! \$\endgroup\$
    – Shaggy
    Jul 9, 2017 at 21:51
  • 4
    \$\begingroup\$ I'm sure the number of golfers who'll read the entire explanation will be smaller than your bytes :D \$\endgroup\$ Jul 10, 2017 at 11:05
  • 2
    \$\begingroup\$ This is absolutely the best language for the job. To help you cut it down in size, take a look at the Babylonian method for calculating square roots. I did a quick test and Equal's Corner returns false for 1/1000000000 = 2/1000000000 but converting them to strings and comparing at Crime Lab returns true. I bet it's shorter to repeatedly apply the method, check if it equal's the last result, and escape once it does. I'll try to write up just a square root function using the method and see what comes out. \$\endgroup\$ Jul 10, 2017 at 16:10
10
\$\begingroup\$

Javascript (ES6), 36 bytes

-1 byte thanks to @dtkaias

(x,y,s=Math.hypot)=>s(x)+s(y)-s(x,y)

Example code snippet:

f=

(x,y,s=Math.hypot)=>s(x)+s(y)-s(x,y)

for(i=0;i<7;i++)
  a=[3,-3,-3,6,42,10,3][i],
  b=[4,4,-4,6,0,10,3][i],
  console.log(`f(${a},${b}) = ${f(a,b)}`)

\$\endgroup\$
6
  • \$\begingroup\$ ES6 doesn't have **. \$\endgroup\$
    – Neil
    Jul 8, 2017 at 21:20
  • 2
    \$\begingroup\$ A true ES6 version would probably be 41 bytes: (x,y,s=Math.sqrt)=>s(x*=x)+s(y*=y)-s(x+y). \$\endgroup\$
    – Neil
    Jul 8, 2017 at 21:21
  • \$\begingroup\$ @DanEsparza It clearly used to. This is what revision history is for... \$\endgroup\$
    – Neil
    Jul 10, 2017 at 19:21
  • \$\begingroup\$ Why not a=>b=>a+b-Math.hypot(a,b)? \$\endgroup\$
    – dtkaias
    Jul 11, 2017 at 1:20
  • 1
    \$\begingroup\$ Right, how about (x,y,s=Math.hypot)=>s(x)+s(y)-s(x,y), for 36 bytes, ES6 compatible too \$\endgroup\$
    – dtkaias
    Jul 11, 2017 at 12:56
8
\$\begingroup\$

Julia, 20 bytes

x->norm(x,1)-norm(x)

Takes a and b as a list.

Julia's norm second argument defaults to 2 - hence this would be equivalent to norm(x, 1) - norm(x, 2).

\$\endgroup\$
2
  • \$\begingroup\$ I also thought about using Julia! \$\endgroup\$
    – enedil
    Jul 8, 2017 at 22:57
  • \$\begingroup\$ Very similar to the MATLAB answer I was about to post. \$\endgroup\$ Jul 10, 2017 at 17:57
6
\$\begingroup\$

Java 8, 47 bytes

Golfed:

(a,b)->(a<0?-a:a)+(b<0?-b:b)-Math.sqrt(a*a+b*b)

This is about as basic as it gets: subtract the two calculated values to find the difference. This uses ternary logic instead of Math.abs() to save one byte each occurrence. Unfortunately, the parentheses are required due to operator precedence.

The output is whatever Java's double can hold, which is accurate to more than two decimal places and satisfies the accuracy requirement of the question.

Ungolfed:

public class TheCrowVsTheTaxicab {

  public static void main(String[] args) {
    int[][] inputs = new int[][] { { 3, 4 }, { -3, 4 }, { -3, -4 }, { 6, 6, }, { 42, 0 }, { 10, 10 }, { 3, 3 } };
    double[] outputs = new double[] { 2, 2, 2, 3.51, 0, 5.85, 1.76 };

    for (int i = 0; i < inputs.length; ++i) {
      double actual =
        f((a, b) -> (a < 0 ? -a : a) + (b < 0 ? -b : b) - Math.sqrt(a * a + b * b), inputs[i][0], inputs[i][1]);

      System.out.println("Input:    " + inputs[i][0] + ", " + inputs[i][1]);
      System.out.println("Expected: " + outputs[i]);
      System.out.println("Actual:   " + actual);
      System.out.println();
    }
  }

  private static double f(java.util.function.BiFunction<Integer, Integer, Double> f, int a, int b) {
    return f.apply(a, b);
  }
}

Output:

Input:    3, 4
Expected: 2.0
Actual:   2.0

Input:    -3, 4
Expected: 2.0
Actual:   2.0

Input:    -3, -4
Expected: 2.0
Actual:   2.0

Input:    6, 6
Expected: 3.51
Actual:   3.5147186257614305

Input:    42, 0
Expected: 0.0
Actual:   0.0

Input:    10, 10
Expected: 5.85
Actual:   5.857864376269049

Input:    3, 3
Expected: 1.76
Actual:   1.7573593128807152
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can use currying to save a byte: a->b->. \$\endgroup\$
    – Jakob
    Aug 21, 2017 at 5:59
5
\$\begingroup\$

R, 30 bytes

function(v)norm(v)-norm(v,'f')

Takes v as a 1-column matrix. norm computes a particular norm of a matrix, with the default being the L1 norm (taxicab), and f the L2 norm ('f' for Frobenius/Euclidean).

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Wow, R has both built-in, nice! \$\endgroup\$
    – BLT
    Jul 11, 2017 at 3:20
4
\$\begingroup\$

Mathematica, 32 bytes

N[Tr@Abs[a={##1}]-Sqrt@Tr[a^2]]&

or

Mathematica, 31 bytes

N[Abs@#+Abs@#2-Sqrt[#^2+#2^2]]&

or @Not a tree's suggestion

Mathematica, 26 bytes

N[Tr@Abs@{##}-Abs[#+I#2]]&

or @alephalpha's suggestion

Mathematica, 19 bytes

N[#~Norm~1-Norm@#]&
\$\endgroup\$
3
  • \$\begingroup\$ Nice work! You can save a few bytes by using complex numbers for the euclidean part: N[Tr@Abs@{##}-Abs[#+I#2]]& \$\endgroup\$
    – Not a tree
    Jul 9, 2017 at 0:00
  • 2
    \$\begingroup\$ N[#~Norm~1-Norm@#]&. \$\endgroup\$
    – alephalpha
    Jul 9, 2017 at 3:17
  • 2
    \$\begingroup\$ @alephalpha #~Norm~1-N@Norm@#& maybe? \$\endgroup\$ Jul 9, 2017 at 7:15
4
\$\begingroup\$

Dyalog APL, 13 bytes

+/∘|-.5*⍨+.×⍨

Try it online!

Explanation (input X):

+/∘|     - Sum of the element-wise absolute value of X
-        - Minus
.5*⍨+.×⍨ - Euclidean distance = sqrt(X . X)
\$\endgroup\$
4
\$\begingroup\$

Python 2, 40 38 36 bytes

-2 bytes thanks to vaultah. -2 bytes thanks to sTertooy.

Fun fact, 11 bytes of this code were just copied from the question and golfed.

lambda a,b:abs(a)+abs(b)-abs(a+b*1j)

Try it online!

\$\endgroup\$
6
  • 1
    \$\begingroup\$ I have been ninja'd \$\endgroup\$
    – Mr. Xcoder
    Jul 8, 2017 at 20:47
  • \$\begingroup\$ @Mr.Xcoder I wouldn't be too worried about it, I'll probably be out-golfed. :P \$\endgroup\$ Jul 8, 2017 at 20:48
  • \$\begingroup\$ @vaultah Oh, good point. Thanks! \$\endgroup\$ Jul 8, 2017 at 20:48
  • 7
    \$\begingroup\$ abs(a+b*1j) should work instead of (a*a+b*b)**.5 \$\endgroup\$
    – sTertooy
    Jul 9, 2017 at 23:08
  • 1
    \$\begingroup\$ @totallyhuman bruh golf it alr \$\endgroup\$
    – ASCII-only
    Oct 21, 2020 at 16:47
3
\$\begingroup\$

Japt, 11 9 bytes

-2 bytes thanks to @ETHproductions

Nxa -MhUV

Try it online!

Explained

Nxa -MhUV   // implicit: U and V are input integers, N = [U,V]

N a         // get absolute value of both inputs
 x          // sum those values
    -MhUV   // subtract hypot(U, V) -> sqrt(U^2 + V^2)
\$\endgroup\$
5
  • \$\begingroup\$ Nice, I think this is the first time I've seen Mh used. I believe you can shorten Ua +Va to Nxa (sum of inputs, running a on each) \$\endgroup\$ Jul 8, 2017 at 20:53
  • \$\begingroup\$ @ETHproductions Oh right, forgot that sum had the optional map parameter. Thanks! \$\endgroup\$ Jul 8, 2017 at 21:01
  • \$\begingroup\$ So there *is" a use for Mh! :D Most methods in Japt can take what @ETHproductions calls an "auto-function" as an argument. See this tip for more on them. And I'll be writing up a tip tomorrow on using auto-functions with array reduction to achieve some interesting results (e.g., rw will return the largest integer in an array). \$\endgroup\$
    – Shaggy
    Jul 9, 2017 at 21:42
  • \$\begingroup\$ @Shaggy Thanks, I had the basic idea of "auto-functions" but didn't realize there was a post for Japt tips. Gonna definitely look through that post. \$\endgroup\$ Jul 9, 2017 at 21:50
  • \$\begingroup\$ We still have a good bit of work to do on that question so if you have something that you feel could be added, please do. Or if you have a query that you think would fit in there, let us know in the comments or join us in the chatroom. \$\endgroup\$
    – Shaggy
    Jul 9, 2017 at 21:55
3
\$\begingroup\$

Scheme - 58 bytes.

(define (f a b) (-(+(abs a)(abs b))(sqrt(* a a)(* b b))))
\$\endgroup\$
4
  • 3
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ Jul 9, 2017 at 12:05
  • \$\begingroup\$ You can remove two spaces - one between the define and the (, and one between the ) and the (. \$\endgroup\$
    – clismique
    Jul 10, 2017 at 12:09
  • \$\begingroup\$ Error: sqrt: too many arguments (at most: 1 got: 2) [f, sqrt] \$\endgroup\$
    – Aaron
    Jul 11, 2017 at 8:18
  • \$\begingroup\$ (lambda(a b)(...)) should be sufficient instead of binding it to a name. Also, (sqrt(* a a b b)) would save a couple bytes. \$\endgroup\$ Aug 30, 2017 at 16:49
3
\$\begingroup\$

Pyth, 8 bytes

-s.aMQ.a

Try it online. Test suite.

Explanation

-s.aMQ.aQ      Q (input) appended implicitly
  .aMQ         absolute values of input vector
 s             sum
-              subtract
      .aQ      norm2 of input vector
\$\endgroup\$
3
\$\begingroup\$

APL (Dyalog), 14 bytes

Takes argument in the form xJy, e.g. 3J4

||-2+/∘|9 11○⊢

Try it online!

| the magnitude ofDoc

| the argument's magnitude

- minus

2+/ the pair-wise sum

 of

| the magnitudes of

9 11.○⊢ the the argument's real and the imaginary parts.Doc

Special trick for golfing was the use of the pairwise reduction (2+/) to supply +/ with a no-op left argument, thereby avoiding parentheses: ||-(+/∘|9 11○⊢)

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

J, 13 bytes

+/@:|-+/&.:*:

This is a function that takes the coordinates as an array, e.g.:

   (+/@:|-+/&.:*:) _3 4
2

Explanation:

+/             sum
  @:           of
    |          absolutes
     -         minus
      +/       sum
        &.:    under
           *:  square
\$\endgroup\$
1
  • \$\begingroup\$ Nice use of &.: -- I wasn't aware of the : of Under. \$\endgroup\$
    – Jonah
    Jul 9, 2017 at 20:53
3
\$\begingroup\$

J, 9 8 bytes

-1 thanks to my colleague Marshall.

+&|-|@j.

Try it online!

Takes A as left argument and B as right argument.

+ the sum

& of

| the magnitudes

- minus

| the magnitude

@ of

j.A + B i

Golfing trick: combine the values to a single complex number because the diagonal is easy to get like that, while also keeping them separate because the sum is easy to get like that.

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

05AB1E, 7 bytes

ÄO¹nOt-

Try it online!

Explanation

Ä        # absolute value of inputs
 O       # sum
  ¹      # push input again
   n     # square
    O    # sum
     t   # sqrt
      -  # subtract
\$\endgroup\$
2
\$\begingroup\$

TI-Basic (TI-84 Plus CE), 10 bytes

sum(abs(Ans))-√(sum(Ans2

Program that input as a list of two integers in Ans, e.g. call with {3,4}:prgmCROW (replacing 3,4 with the input and CROW with the name of the program).

Explanation:

sum(abs(Ans))-√(sum(Ans2
        Ans               # The input list of two integers
    abs(   )              # Absolute value of each item in the list
sum(        )             # Sum of the list
                    Ans   # The input list of two integers
                       2  # Square of each item in the list
                sum(      # Sum of the list
              √(          # Square root of the sum
             -            # Difference of the two values
\$\endgroup\$
3
  • \$\begingroup\$ That looks like 24-26 bytes to me, depending on how and $Ans^2$ are encoded . 10 keystrokes, perhaps, but that's not the same thing. \$\endgroup\$
    – Ray
    Jul 11, 2017 at 0:01
  • \$\begingroup\$ @Ray TI-Basic is a tokenized language. \$\endgroup\$ Jul 11, 2017 at 0:08
  • \$\begingroup\$ I'm mostly familiar with TI-89 Basic, where that isn't the case. Objection withdrawn. \$\endgroup\$
    – Ray
    Jul 11, 2017 at 0:10
2
\$\begingroup\$

MATL, 8 7 bytes

|sG2&|-

Try it online!

Explanation

|    % Implicit input: vector of two numbers. Absolute value, element-wise
s    % Sum of vector
G    % Push input again
2    % Push 2
&|   % 2-norm of input
-    % Subtract. Implicit display
\$\endgroup\$
2
\$\begingroup\$

Common Lisp, 57 bytes

(defun g(a b)(+(abs a)(abs b)(-(sqrt(+(* a a)(* b b))))))

Try it online!

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

Jelly, 7 bytes

²S½ạAS$

Try it online!

Format is list of two numbers.

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

GNU APL 1.2, 24 bytes

∇f P
(+/|P)-(+/P*2)*.5
∇

∇f P declares a function f that takes a vector P containing the distances as an argument (e.g. [3, 4])

APL operates on vectors, so +/|P applies the | operator (abs function) to each element in the vector and then evaluates + on each element (so add all the elements). This gives the taxi distance.

P*2 yields a vector that is the same as P but with each element squared. +/P*2 to add those together and then (with parentheses for precedence because APL is right-to-left) *.5 to get the square root. This gives the crow distance.

Add an extra pair of parentheses for the taxi distance for precedence and compute the difference.

to end the function.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Can't you use an anonymous lambda? {(+/|⍵)-(+/⍵*2)*.5}? \$\endgroup\$
    – Adám
    Jul 10, 2017 at 21:51
  • \$\begingroup\$ @Adám I don't have a lot of experience with APL and the newest version of the GNU interpreter (1.7) won't compile on Mac, so there might be some limitations. I'll try later to see if it works. Thanks for the tip. \$\endgroup\$
    – Arc676
    Jul 12, 2017 at 13:07
  • \$\begingroup\$ Almost all features of GNU APL are also in Dyalog APL, which is freely available on Mac. You can also try it online. \$\endgroup\$
    – Adám
    Jul 12, 2017 at 13:10
  • \$\begingroup\$ Also, feel free to join the APL chat room to learn more APL. \$\endgroup\$
    – Adám
    Jul 12, 2017 at 13:10
2
\$\begingroup\$

Add++, 59 57 bytes

D,f,@@,|@|+
D,g,@@,d*@d*+
_
$f>G>G
V
$g>?>?
S
-G
$f>x>0
O

Try it online!

This took me ages to solve. It doesn't round the final answer as that isn't possible in Add++. This is how the program works with the inputs -3 and -4 (ACC is the accumulator value)

D,        Define a function
  f,      called f
  @@,     that takes 2 arguments (e.g. -3, -4)
     |    absolute value;   STACK = [-3, 4]
     @    reverse stack;    STACK = [4, -3]
     |    absolute value;   STACK = [4, 3]
     +    sum;              STACK = [7]
          implicitly return the top of the stack

D,        Define a function
  g,      called g
  @@,     that takes 2 arguments (e.g. -3, -4)
     d    duplicate;  STACK = [-3, -4, -4]
     *    multiply;   STACK = [-3, 16]
     @    reverse;    STACK = [16, -3]
     d    duplicate;  STACK = [16, -3, -3]
     *    multiply;   STACK = [16, 9]
     +    sum;        STACK = [25]
          implicitly return the top of the stack

_         store the inputs in the second stack;  ACC = 0;  STACK = [-3, -4]
$f>G>G    apply f with -3 and -4 as arguments;   ACC = 7;  STACK = []
V         store ACC in the stack;                ACC = 7;  STACK = [7]
$g>?>?    apply g with -3 and -4 as arguments;   ACC = 25; STACK = [7]
S         square root the ACC;                   ACC = 5;  STACK = [7]
-G        subtract the stack value from the ACC; ACC = -2; STACK = []
$f>x>0    apply f with ACC and 0 as arguments;   ACC = 2;  STACK = []
O         output ACC as a number
\$\endgroup\$
2
\$\begingroup\$

Pyth, 7 bytes

a.aQsa0

Try it here


Pyth,  25  23 bytes

THis is the initial solution, my first not-so-trivial Pyth solution and you can see just how bad I used to be at golfing in Pyth :)

K.aswJ.asw-+KJ^+^K2^J2 .5

Try it online!

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

Pip, 15 bytes

ABa+ABb-RT$+g*g

Takes input from command-line arguments. Try it online!

Explanation

In pseudocode, this is abs(a) + abs(b) - sqrt(fold+(g*g)). a and b are the first two cmdline args, and g is the list of cmdline args (i.e. argv). The * operator vectorizes, like many Pip operators, so $+g*g is the same thing as a*a + b*b. The rest is pretty straightforward.

Unfortunately, I can't save any bytes with $+ABg, because the precedence of operators with fold doesn't work like it should yet. $+ ought to be slightly higher precedence than binary -, but at the moment it parses as $+(ABg-RT$+g*g), giving the wrong answer. Doing ($+ABg)-RT$+g*g doesn't save any bytes over the less-obfuscated version above.

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

PHP>=7.1, 54 bytes

[,$x,$y]=$argv;echo abs($x)+abs($y)-sqrt($x**2+$y**2);

PHP Sandbox Online

PHP, 55 bytes

<?=abs($x=$argv[1])+abs($y=$argv[2])-sqrt($x**2+$y**2);

Try it online!

PHP, 60 bytes

with an function instead of a full program

function f($x,$y){return abs($x)+abs($y)-sqrt($x**2+$y**2);}

Try it online!

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

Excel VBA, 34 Bytes

Anonymous VBE immediate window function that takes input from range [A1:B1] and outputs the difference between the Euclidean and Taxicab distances to the VBE immediate window.

?[ABS(A1)+ABS(B1)-SQRT(A1^2+B1^2)]
\$\endgroup\$
2
  • 1
    \$\begingroup\$ It's two bytes shorter to put it directly in a cell in the sheet: =ABS(A1)+ABS(B1)-SQRT(A1^2+B1^2) \$\endgroup\$ Jul 11, 2017 at 14:09
  • \$\begingroup\$ @EngineerToast, I thought that I had already put up my Google Sheets/ Excel Solutions - thanks for pointing this out \$\endgroup\$ Jul 12, 2017 at 10:40
1
\$\begingroup\$

,,,, 18 bytes

Essentially a port of my Python answer.

a:↔a:0•2*⇆2*+√↔+↔-
\$\endgroup\$
1
\$\begingroup\$

Forth (gforth), 68 bytes

abs swap abs 2dup + s>d d>f dup * swap dup * + s>d d>f fsqrt  f- f.s

Try it online !

The coordinates are two numbers on the stack.

PS my first code golf... don't hit too hard ;-)!

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

Ruby, 31 bytes

Creates a complex number to calculate the distance with.

->x,y{x.abs+y.abs-(x+y*1i).abs}

Try it online!

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

Ruby (2.0.0 - 2.3.0), 57bytes

x,y=$*.map(&:to_i);puts x.abs+y.abs-Math.sqrt(x**2+y**2)

This assumes taking input from ARGV e.g.

ruby -e 'x,y=$*.map(&:to_i);puts x.abs+y.abs-Math.sqrt(x**2+y**2)' -- -3 4

This feels like a cheat since Ruby comes with a math lib that has abs and sqrt functions (unlike the guy who wrote his own abs and sqrt functions, though I didn't see anything specifically forbidding the use of such functions).

The first trick is using .map instead of .each which saves a byte, then using the &:symbol notation to pass map a proc we execute to_i on each item in the array, and use multiple assignment to assign values to x and y.

A longer version would be:

(x, y) = ARGV.map{ |string| string.to_i }

(since map returns an array, multiple assignment is probably the way to do it, this does throw away any additional parameters, but we're assuming only two inputs anyway)

Then I just removed all of the spaces in the equation.

Here's a longer version, 84 bytes

$*.map!(&:to_i);puts$*.inject(0){|x,y|x+y.abs}-Math.sqrt($*.inject(0){|x,y|x+y**2})

The goal here was to not repeat myself, e.g. having to write x or abs twice and my squaring twice x**2 + y**2

It did not work.

But what's interesting is that puts doesn't need a space, I guess the lexer is smart enough to see the special char and know it's a special var.

inject and reduce are synonyms, inject has a signature of

inject(initial) {| memo, obj | block }

In our case we need to set the initial to 0, then we have our accumulator (i.e.: memo = 0) and the object from each iteration.

The down side to this method is that it will take more than two inputs and will either sum or square, add, then sqrt all the values in the array.

I think--though I don't have a Ruby 2.4.0 to test with--that this will work as well, which comes in at 72 bytes:

$*.map!(&:to_i);puts$*.sub{|x,y|x+y.abs}-Math.sqrt($*.sum{|x,y|x+y**2})

Sum defaults to 0 and as far as I can tell, works the same as inject/reduce.

\$\endgroup\$
3
  • \$\begingroup\$ The only reason he didn't use builtins was because that language didn't have any available for him to use. Nice answer, and welcome to PPCG! :) \$\endgroup\$ Jul 11, 2017 at 0:22
  • \$\begingroup\$ Welcome to PPCG! The TIO Portal has a working Ruby 2.4.0 that you can use to try things out online. Try it here \$\endgroup\$
    – Value Ink
    Aug 5, 2017 at 4:01
  • \$\begingroup\$ Taking advantage of the flexible i/o requirements, you could avoid parsing and puts-ing, golfing down to a 35-byte lambda. \$\endgroup\$
    – benj2240
    Feb 15, 2018 at 22:19
1
\$\begingroup\$

Google Sheets, 31 Bytes

Worksheet function that takes input from range [A1:B1] and outputs the difference between the Euclidean and Taxicab distances

=ABS(A1)+ABS(B1)-SQRT(A1^2+B1^2

Excel, 32 bytes

Same as above but formatted for MS Excel

=ABS(A1)+ABS(B1)-SQRT(A1^2+B1^2)
\$\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.