The Crow vs The Taxicab

36

3

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

James

Posted 2017-07-08T20:35:07.910

Reputation: 54 537

9can we take input as complex number? – Uriel – 2017-07-08T20:45:31.563

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. – numbermaniac – 2017-07-09T05:31:32.493

4I first read the title as The Cow vs The Taxicab and was hoping to find something involving collision physics... – MooseBoys – 2017-07-10T06:02:45.573

May we give negative results? – Adám – 2017-07-10T22:11:29.150

@Adám No. (Since conceptually, you're returning a distance, which is always positive) – James – 2017-07-10T22:13:15.197

@Uriel Sorry I didn't respond earlier. I guess I don't have any problem with giving the input as a complex number. – James – 2017-07-10T22:14:05.667

@DJMcMayhem Then how can the input be negative‽ – Adám – 2017-07-10T22:30:08.447

@Adám because the input represents points on a Cartesian coordinate system. – James – 2017-07-10T22:31:43.123

@DJMcMayhem And the output represents a distance on a Cartesian coordinate system. – Adám – 2017-07-10T22:34:03.880

@Adám the Lp norms are always positive – Maltysen – 2017-08-30T21:46:52.987

Answers

107

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.

Stephen

Posted 2017-07-08T20:35:07.910

Reputation: 12 293

1This is insane... – Gryphon – 2017-07-09T16:51:31.150

2@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 – Stephen – 2017-07-09T17:05:25.497

Explanations added - let me know if you have questions – Stephen – 2017-07-09T21:21:07.660

44 hours is deserving of the +1 in itself! – Shaggy – 2017-07-09T21:51:45.873

4I'm sure the number of golfers who'll read the entire explanation will be smaller than your bytes :D – Grajdeanu Alex. – 2017-07-10T11:05:46.220

1+1 for -1 is waiting at Starchild Numerology. – Keyu Gan – 2017-07-10T15:26:39.477

1

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.

– Engineer Toast – 2017-07-10T16:10:05.137

@EngineerToast thanks :) Yup, you're probably right - I didn't completely understand the Babylonian method when I looked at it, so I didn't try it. I'm going to be gone for a week in the woods - if you get it working, feel free to edit it in. You're probably much better at Taxi then I am, I learned it as I went. The biggest thing to cut down on bytes would be reusing the absolute value bit, since that's just copied and pasted with changed labels. (Not saying you should do it, just saying that that's how I would golf it :P ) – Stephen – 2017-07-10T16:13:38.167

I understood it enough to replicate the method in Excel but it's proving to be a pain in Taxi. For Excel, put the value in A1 and the following formula in A2: =(A1+($A$1/A1))/2. Drag that down and you'll see it iterate towards the square root. I'm not in a mental stae to keep track of those passengers right now, though, so I'll give it a go tomorrow. – Engineer Toast – 2017-07-10T20:54:53.117

1Now here's the real question: What is the taxicab distance of the route you travel in this answer itself? :P Nice job btw! – James – 2017-07-10T22:15:45.163

@DJMcMayhem If someone wants to modify the C++ interpreter on the developer's site, they could have it output miles_driven since it's already being tracked to make sure you don't run out of gas.

– Engineer Toast – 2017-07-11T14:03:01.087

1

I got the square root function but the TIO link is way too big to paste here. The comments version is at https://goo.gl/PjdepM (check the link safety at http://wheredoesthislinkgo.com if you wish). The golfed version is 1,590 bytes and can be tested here: https://goo.gl/6TKwfV. I'll work on integrating it to yours to see if it's shorter.

– Engineer Toast – 2017-07-12T15:33:11.810

1

OK, I have a Taxi answer that comes in at 3,773 bytes. I want to give it to you. Golfed version: https://pastebin.com/D2UuUCVp Ungolfed version with comments: https://pastebin.com/yJt1iwUj For future reference, he's my ungolfed square root function, too: https://pastebin.com/n4b24h3V Please keep golfing in Taxi. You're only the 4th user to ever post an answer in Taxi. One quick hint: You don't have to go back to the garage unless OP specifically restricts output to stderr.

– Engineer Toast – 2017-07-12T20:33:53.760

@EngineerToast thanks! I just got back, I'll edit it in. After reading it, that's so much smarter than what I was trying to do - I really didn't utilize the "If no passenger are waiting", or The Underground. – Stephen – 2017-07-17T01:11:22.370

10

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)}`)

Herman L

Posted 2017-07-08T20:35:07.910

Reputation: 3 611

ES6 doesn't have **. – Neil – 2017-07-08T21:20:40.560

2A true ES6 version would probably be 41 bytes: (x,y,s=Math.sqrt)=>s(x*=x)+s(y*=y)-s(x+y). – Neil – 2017-07-08T21:21:42.877

@DanEsparza It clearly used to. This is what revision history is for... – Neil – 2017-07-10T19:21:38.550

Why not a=>b=>a+b-Math.hypot(a,b)? – dtkaias – 2017-07-11T01:20:34.493

@dtkaias a=>b=>a+b-Math.hypot(a,b) would not work for negative numbers. – Herman L – 2017-07-11T06:27:54.020

1Right, how about (x,y,s=Math.hypot)=>s(x)+s(y)-s(x,y), for 36 bytes, ES6 compatible too – dtkaias – 2017-07-11T12:56:58.880

8

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

Uriel

Posted 2017-07-08T20:35:07.910

Reputation: 11 708

I also thought about using Julia! – enedil – 2017-07-08T22:57:40.960

Very similar to the MATLAB answer I was about to post. – TheIncredibleZ1 – 2017-07-10T17:57:30.207

6

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

user18932

Posted 2017-07-08T20:35:07.910

Reputation:

1You can use currying to save a byte: a->b->. – Jakob – 2017-08-21T05:59:32.183

4

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@#]&

J42161217

Posted 2017-07-08T20:35:07.910

Reputation: 15 931

Nice work! You can save a few bytes by using complex numbers for the euclidean part: N[Tr@Abs@{##}-Abs[#+I#2]]& – Not a tree – 2017-07-09T00:00:19.933

2N[#~Norm~1-Norm@#]&. – alephalpha – 2017-07-09T03:17:02.533

2@alephalpha #~Norm~1-N@Norm@#& maybe? – Martin Ender – 2017-07-09T07:15:27.863

4

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)

Zacharý

Posted 2017-07-08T20:35:07.910

Reputation: 5 710

4

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!

Giuseppe

Posted 2017-07-08T20:35:07.910

Reputation: 21 077

Wow, R has both built-in, nice! – BLT – 2017-07-11T03:20:33.520

3

Python 2, 40 38 bytes

-2 bytes thanks to vaultah.

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

lambda a,b:abs(a)+abs(b)-(a*a+b*b)**.5

Try it online!

totallyhuman

Posted 2017-07-08T20:35:07.910

Reputation: 15 378

1

I have been ninja'd

– Mr. Xcoder – 2017-07-08T20:47:02.217

@Mr.Xcoder I wouldn't be too worried about it, I'll probably be out-golfed. :P – totallyhuman – 2017-07-08T20:48:27.103

@vaultah Oh, good point. Thanks! – totallyhuman – 2017-07-08T20:48:47.547

5abs(a+b*1j) should work instead of (a*a+b*b)**.5 – SteamyRoot – 2017-07-09T23:08:22.460

3

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)

Justin Mariner

Posted 2017-07-08T20:35:07.910

Reputation: 4 746

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) – ETHproductions – 2017-07-08T20:53:49.507

@ETHproductions Oh right, forgot that sum had the optional map parameter. Thanks! – Justin Mariner – 2017-07-08T21:01:15.350

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

– Shaggy – 2017-07-09T21:42:19.757

@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. – Justin Mariner – 2017-07-09T21:50:40.857

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.

– Shaggy – 2017-07-09T21:55:30.620

3

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

marinus

Posted 2017-07-08T20:35:07.910

Reputation: 30 224

Nice use of &.: -- I wasn't aware of the : of Under. – Jonah – 2017-07-09T20:53:49.080

3

Scheme - 58 bytes.

(define (f a b) (-(+(abs a)(abs b))(sqrt(* a a)(* b b))))

GenRincewind

Posted 2017-07-08T20:35:07.910

Reputation: 31

3Welcome to PPCG! – Martin Ender – 2017-07-09T12:05:14.403

You can remove two spaces - one between the define and the (, and one between the ) and the (. – clismique – 2017-07-10T12:09:28.743

Error: sqrt: too many arguments (at most: 1 got: 2) [f, sqrt] – Aaron – 2017-07-11T08:18:50.123

(lambda(a b)(...)) should be sufficient instead of binding it to a name. Also, (sqrt(* a a b b)) would save a couple bytes. – Daniel Schepler – 2017-08-30T16:49:48.557

3

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

PurkkaKoodari

Posted 2017-07-08T20:35:07.910

Reputation: 16 699

3

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○⊢)

Adám

Posted 2017-07-08T20:35:07.910

Reputation: 37 779

2

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

Emigna

Posted 2017-07-08T20:35:07.910

Reputation: 50 798

2

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

Luis Mendo

Posted 2017-07-08T20:35:07.910

Reputation: 87 464

2

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

pizzapants184

Posted 2017-07-08T20:35:07.910

Reputation: 3 174

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. – Ray – 2017-07-11T00:01:28.883

@Ray TI-Basic is a tokenized language.

– pizzapants184 – 2017-07-11T00:08:18.397

I'm mostly familiar with TI-89 Basic, where that isn't the case. Objection withdrawn. – Ray – 2017-07-11T00:10:43.820

2

Common Lisp, 57 bytes

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

Try it online!

Renzo

Posted 2017-07-08T20:35:07.910

Reputation: 2 260

2

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.

Arc676

Posted 2017-07-08T20:35:07.910

Reputation: 301

1Can't you use an anonymous lambda? {(+/|⍵)-(+/⍵*2)*.5}? – Adám – 2017-07-10T21:51:11.160

@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. – Arc676 – 2017-07-12T13:07:07.933

Almost all features of GNU APL are also in Dyalog APL, which is freely available on Mac. You can also try it online.

– Adám – 2017-07-12T13:10:11.423

Also, feel free to join the APL chat room to learn more APL.

– Adám – 2017-07-12T13:10:52.813

2

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

caird coinheringaahing

Posted 2017-07-08T20:35:07.910

Reputation: 13 702

2

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.

Adám

Posted 2017-07-08T20:35:07.910

Reputation: 37 779

1

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!

Jörg Hülsermann

Posted 2017-07-08T20:35:07.910

Reputation: 13 026

1

,,,, 18 bytes

Essentially a port of my Python answer.

a:↔a:0•2*⇆2*+√↔+↔-

totallyhuman

Posted 2017-07-08T20:35:07.910

Reputation: 15 378

1

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

Taylor Scott

Posted 2017-07-08T20:35:07.910

Reputation: 6 709

1It's two bytes shorter to put it directly in a cell in the sheet: =ABS(A1)+ABS(B1)-SQRT(A1^2+B1^2) – Engineer Toast – 2017-07-11T14:09:20.943

@EngineerToast, I thought that I had already put up my Google Sheets/ Excel Solutions - thanks for pointing this out – Taylor Scott – 2017-07-12T10:40:28.030

1

Pari/GP, 26 bytes

x->normlp(x,1)-normlp(x,2)

Try it online!

alephalpha

Posted 2017-07-08T20:35:07.910

Reputation: 23 988

1

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!

Mr. Xcoder

Posted 2017-07-08T20:35:07.910

Reputation: 39 774

1

Jelly, 7 bytes

²S½ạAS$

Try it online!

Format is list of two numbers.

Erik the Outgolfer

Posted 2017-07-08T20:35:07.910

Reputation: 38 134

1

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!

Value Ink

Posted 2017-07-08T20:35:07.910

Reputation: 10 608

1

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.

qubitrenegade

Posted 2017-07-08T20:35:07.910

Reputation: 11

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! :) – Conor O'Brien – 2017-07-11T00:22:55.093

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

– Value Ink – 2017-08-05T04:01:54.307

Taking advantage of the flexible i/o requirements, you could avoid parsing and puts-ing, golfing down to a 35-byte lambda.

– benj2240 – 2018-02-15T22:19:40.520

1

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)

Taylor Scott

Posted 2017-07-08T20:35:07.910

Reputation: 6 709

0

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.

DLosc

Posted 2017-07-08T20:35:07.910

Reputation: 21 213

0

Casio-Basic, 27 bytes

abs(a)+abs(b)-norm([a,b]

Turns out you can just leave off that last bracket and it'll work fine. Having norm as a built-in makes it even shorter!

24 bytes for the code, 3 bytes to add a,b as parameters.

numbermaniac

Posted 2017-07-08T20:35:07.910

Reputation: 639

0

QBIC, 27 bytes

?abs(:)+abs(:)-sqr(a^2+b^2)

steenbergh

Posted 2017-07-08T20:35:07.910

Reputation: 7 772

0

Scala 8, 48 bytes

a=>b=>Math.abs(a)+Math.abs(b)-Math.sqrt(a*a+b*b)

Explained:

a=>b=>                   A curried function with two parameters, 'a' and 'b'.
Math.abs(a)              The absolute value of 'a'.
+Math.abs(b)             Plus the absolute value of 'b'.
-Math.sqrt(a*a+b*b)      Minus the squareroot of 'a' squared plus 'b' squared.

I'm not very experienced with Scala for there is probably a few improvements that could be made.

Llew Vallis

Posted 2017-07-08T20:35:07.910

Reputation: 131

0

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 ;-)!

Rmano

Posted 2017-07-08T20:35:07.910

Reputation: 101

0

ExtraC, 82 bytes

import math
lambda dbl f,x,y,abs(x)plus abs(y)minus sqrt(x times x plus y times y)

Try it online!

Presenting my new language, ExtraC! It's supposed to look like python, but it's really just C. Oh, and it has almost no symbols available to it.

Simply put, this imports the math library (for sqrt), and defines a function f which takes two integers and returns a double.

Example usage:

import math
lambda dbl f,x,y,abs(x)plus abs(y)minus sqrt(x times x plus y times y)
// end submission
let x be readint, y be readint
disp(f(x, y))

Which, for input 3 3 would output: 1.75736 Try it online!

Conor O'Brien

Posted 2017-07-08T20:35:07.910

Reputation: 36 228

0

Java 7, 92 73 bytes

double c(int a,int b){return Math.abs(a)+Math.abs(b)-Math.sqrt(a*a+b*b);}

Ungolfed, I think it is self explanatory:

double c(int a,int b){
    return Math.abs(a)+Math.abs(b)-Math.sqrt(a*a+b*b);
}

Java Gonzar

Posted 2017-07-08T20:35:07.910

Reputation: 173

Suggest return(a<0?-a:a)+(b<0?-b:b)-Math.hypot(a,b); instead of return Math.abs(a)+Math.abs(b)-Math.sqrt(a*a+b*b); – ceilingcat – 2019-11-22T20:58:22.290

0

PHP 7, 109 bytes (insane variant)

$a[0]=($s=array_sum)($a=($m=array_map)(function($n){return$n*$n;},$argv));
$a=$m(sqrt,$a);
echo$s([-$a[0]]+$a);

linebreaks are for reading convenience only. Run with -nr.

Titus

Posted 2017-07-08T20:35:07.910

Reputation: 13 814

0

Perl 5, 41 + 2 (-pa) = 43 bytes

$_=abs($F[1])-sqrt($F[0]**2+$F[1]**2)+abs

Try it online!

Xcali

Posted 2017-07-08T20:35:07.910

Reputation: 7 671