Le corbeau vs le taxi


36

Imaginez voyager jusqu'à un point situé A miles de distance horizontalement et B miles à la verticale de votre position actuelle. Ou en d'autres termes, voyager de (0, 0)point à point (a, b). Jusqu'où auriez-vous besoin de finir par voyager? Cela semble être une question simple, mais la réponse dépend de qui vous demandez. Si vous êtes un corbeau, et vous pouvez voyager à vol d'oiseau , la distance parcourue est juste la distance euclidienne à (a, b). C'est

sqrt(a^2 + b^2)

Mais si vous êtes juste un humain ennuyeux, vous ne voulez pas vraiment marcher aussi loin, alors vous devrez prendre un taxi. La plupart des taxis ne conduisent pas en ligne droite vers votre destination car ils essaient généralement de rester sur les routes. Ainsi, la distance réelle à parcourir est la somme de la distance verticale et de la distance horizontale. Ou la formule est:

abs(a) + abs(b)

Ceci s'appelle la distance de taxi . Cette image montre bien la différence entre les deux:

enter image description here

Pour voyager (6, 6), un corbeau peut simplement voler sur la ligne verte, ce qui donne une distance d' 6 * sqrt(2)environ 8,49. Un taxi peut emprunter les sentiers rouge, bleu ou jaune, mais ils emprunteront tous 12 km.

Cela conduit à la vraie question que je pose. Si un corbeau et un taxi partent tous deux d'un point (0, 0)à l'autre (a, b), combien de temps leur chemin est-il long? Ou, dans plus de jargon mathématique,

À partir d’un vecteur bidimensionnel, déterminez la différence entre la norme norm2 du vecteur et la norm1 du vecteur.

Vous devez écrire le programme ou la fonction le plus court possible pour répondre à cette question. Vous pouvez choisir de prendre "a" et "b" comme deux entrées séparées ou comme un tuple à deux éléments. Vous pouvez entrer et sortir dans n'importe quel format raisonnable. Si la différence n'est pas un entier, vous devez être précis à au moins deux décimales.

Vous pouvez toujours supposer que 'a' et 'b' seront des entiers et qu'ils ne seront pas tous les deux égaux à 0. (Bien qu'il soit possible que l'un ou l'autre soit égal à zéro)

Comme d'habitude, des failles standard s'appliquent et tentent de rendre votre programme aussi court que possible, compté en octets.

Je vais upvoter toute réponse qui affiche une explication de la façon dont le code fonctionne, et montre toutes les astuces intéressantes utilisées pour économiser des octets.

Voici quelques exemples pour vous permettre de tester votre code sur:

#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

Amusez-vous à jouer au golf! :)


9
pouvons-nous prendre en entrée un nombre complexe?
Uriel

Je pense que le test 10,10doit être 5.86, car il vient 5.85786...et vous avez arrondi le test en dessous.
numbermaniac

4
J'ai d'abord lu le titre " The Cow vs The Taxicab" et j'espérais trouver quelque chose impliquant la physique des collisions ...
MooseBoys 10/07/17

Peut-on donner des résultats négatifs?
Adám

@ Adám Non. (Depuis conceptuellement, vous retournez une distance toujours positive)
DJMcMayhem

Réponses:


107

Taxi , 7394 3773 octets

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.

Essayez-le en ligne!

Engineer Toast , un golfeur de taxi bien plus expérimenté, a décidé de prendre un peu de temps (probablement beaucoup moins que moi) et de jouer au golf dans mon programme de taxi en le réécrivant. Vous pouvez trouver mon ancien corps de réponse et des liens vers mes anciens TIO dans l'historique des modifications.

Algorithme de racine carrée non golfée de Engineer Toast: essayez-le en ligne!

Ungolfed, avec des explications:

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


2
@Gryphon, la chose la plus folle, c'est que je suis sûr à 100% de pouvoir supprimer deux mille octets une fois que je revisiterai ma logique alors que je ne suis pas à moitié endormi
Stephen

4
4 heures méritent le +1 en soi!
Shaggy

4
Je suis sûr que le nombre de golfeurs qui liront l'intégralité de l'explication sera inférieur à vos octets: D
Grajdeanu Alex.

1
+1 pour-1 is waiting at Starchild Numerology.
Keyu Gan

10

Javascript (ES6), 36 octets

-1 octet grâce à @dtkaias

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

Exemple d'extrait de code:

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


ES6 n'a pas **.
Neil

2
Une véritable version ES6 serait probablement 41 octets: (x,y,s=Math.sqrt)=>s(x*=x)+s(y*=y)-s(x+y).
Neil

@DanEsparza Il était clairement utilisé. C’est à quoi sert l’historique des révisions ...
Neil

Pourquoi ne pas a=>b=>a+b-Math.hypot(a,b)?
dtkaias

1
Bon, que diriez-vous (x,y,s=Math.hypot)=>s(x)+s(y)-s(x,y), pour 36 octets, de la compatibilité ES6 aussi
dtkaias

8

Julia, 20 octets

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

Prend aet bcomme une liste.

Le normsecond argument de Julia vaut 2 par défaut - ce qui équivaut à norm(x, 1) - norm(x, 2).


J'ai aussi pensé à utiliser Julia!
Enedil

Très similaire à la réponse MATLAB que j'étais sur le point de poster.
TheIncredibleZ1

6

Java 8, 47 octets

Golfé:

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

C’est à peu près aussi fondamental que cela: soustrayez les deux valeurs calculées pour trouver la différence. Ceci utilise la logique ternaire au lieu de Math.abs()sauvegarder un octet à chaque occurrence. Malheureusement, les parenthèses sont obligatoires en raison de la priorité de l'opérateur.

La sortie correspond à tout ce que Java doublepeut contenir, ce qui est précis à plus de deux décimales et satisfait à l'exigence de précision de la 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);
  }
}

Sortie:

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

1
Vous pouvez utiliser curryfication pour enregistrer un octet: a->b->.
Jakob

4

Mathematica, 32 octets

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

ou

Mathematica, 31 octets

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

ou @Pas la suggestion d'un arbre

Mathematica, 26 octets

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

ou la suggestion de @ alephalpha

Mathematica, 19 octets

N[#~Norm~1-Norm@#]&

Bon travail! Vous pouvez économiser quelques octets en utilisant des nombres complexes pour la partie euclidienne:N[Tr@Abs@{##}-Abs[#+I#2]]&
Pas un arbre

2
N[#~Norm~1-Norm@#]&.
alephalpha

2
@alephalpha #~Norm~1-N@Norm@#&peut-être?
Martin Ender

4

Dyalog APL, 13 octets

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

Essayez-le en ligne!

Explication (entrée X):

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

4

R , 30 octets

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

Prend vcomme une matrice à 1 colonne. normcalcule une norme particulière d'une matrice, la valeur par défaut étant la norme L1 (taxicab) et fla norme L2 ( 'f'pour Frobenius / Euclidien).

Essayez-le en ligne!


Wow, R a les deux intégrés, sympa!
BLT

3

Python 2 , 40 38 octets

-2 octets grâce à vaultah.

Fait amusant, 11 octets de ce code viennent d'être copiés de la question et joués au golf.

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

Essayez-le en ligne!


1
J'ai été ninja
M. Xcoder

@ Mr.Xcoder Je ne serais pas trop inquiet à ce sujet, je vais probablement jouer au golf. : P
totalement humain

@ vaultah Oh, bon point. Merci!
totalement humain

5
abs(a+b*1j)devrait fonctionner au lieu de(a*a+b*b)**.5
SteamyRoot

3

Japt , 11 à 9 octets

-2 octets grâce à @ETHproductions

Nxa -MhUV

Essayez-le en ligne!

A expliqué

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)

Nice, je pense que c'est la première fois que je vois Mhutilisé. Je crois que vous pouvez réduire Ua +Vaà Nxa(somme des entrées, en cours d' exécution asur chaque)
ETHproductions

@ETHproductions Oh oui, j'ai oublié que la somme avait le paramètre optionnel map. Merci!
Justin Mariner

Donc, il y a * une "utilisation pour Mh!: D La plupart des méthodes de Japt peuvent prendre comme argument ce que @ETHproductions appelle une" fonction automatique ". Voir cette astuce pour en savoir plus. Et j'écrirai une astuce demain en utilisant des fonctions automatiques avec réduction de tableau pour obtenir des résultats intéressants (par exemple, rwrenverra le plus grand entier d'un tableau).
Shaggy

@Shaggy Merci, j'avais l'idée de base des "fonctions automatiques" mais je ne savais pas qu'il y avait un post pour les astuces Japt. Va certainement regarder à travers ce post.
Justin Mariner

Nous avons encore beaucoup de travail à faire sur cette question. Si vous pensez pouvoir ajouter quelque chose, n'hésitez pas. Ou si vous avez une question qui pourrait vous intéresser, faites-le nous savoir dans les commentaires ou rejoignez-nous dans le forum de discussion .
Shaggy

3

Schéma - 58 octets.

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

3
Bienvenue chez PPCG!
Martin Ender

Vous pouvez supprimer deux espaces - un entre le defineet le (, et un entre le )et le (.
clismique

Error: sqrt: too many arguments (at most: 1 got: 2) [f, sqrt]
Aaron

(lambda(a b)(...))devrait être suffisant au lieu de le lier à un nom. En outre, (sqrt(* a a b b))économiser quelques octets.
Daniel Schepler


3

APL (Dyalog) , 14 octets

Prend argument sous la forme xJy, par exemple3J4

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

Essayez-le en ligne!

| la magnitude de doc

| la magnitude de l'argument

- moins

2+/ la somme par paire

 de

| les magnitudes de

9 11.○⊢ l'argument est réel et les parties imaginaires. Doc

Le truc spécial pour le golf était l’utilisation de la réduction par paire ( 2+/) pour fournir +/un argument non-gauche, évitant ainsi les parenthèses:||-(+/∘|9 11○⊢)


3

J, 13 octets

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

C'est une fonction qui prend les coordonnées sous forme de tableau, par exemple:

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

Explication:

+/             sum
  @:           of
    |          absolutes
     -         minus
      +/       sum
        &.:    under
           *:  square

Belle utilisation de &.:- je n'étais pas au courant de la :sous.
Jonah


2

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

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

Programmez cette entrée sous forme de liste de deux entiers Ans, par exemple, appelez avec {3,4}:prgmCROW(remplacez 3,4par l'entrée et CROWpar le nom du programme).

Explication:

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

Cela ressemble à 24-26 octets pour moi, en fonction de la façon dont et $ Ans ^ 2 $ sont codés. 10 frappes peut-être, mais ce n'est pas la même chose.
Ray

@Ray TI-Basic est un langage à jeton .
pizzapants184

Je connais surtout la TI-89 Basic, où ce n'est pas le cas. Objection retirée.
Ray

2

MATL , 8 7 octets

|sG2&|-

Essayez-le en ligne!

Explication

|    % 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


2

GNU APL 1.2, 24 octets

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

∇f Pdéclare une fonction fqui prend Pcomme argument un vecteur contenant les distances (par exemple[3, 4] )

APL fonctionne sur des vecteurs, +/|Papplique donc l' |opérateur ( absfonction) à chaque élément du vecteur, puis évalue +chaque élément (ajoute donc tous les éléments). Cela donne la distance de taxi.

P*2donne un vecteur qui est identique à Pmais avec chaque élément au carré. +/P*2pour les ajouter ensemble (puis entre parenthèses car APL est de droite à gauche) *.5pour obtenir la racine carrée. Cela donne la distance du corbeau.

Ajoutez une paire de parenthèses supplémentaire pour la distance de taxi comme priorité et calculez la différence.

pour terminer la fonction.


1
Ne pouvez-vous pas utiliser un lambda anonyme? {(+/|⍵)-(+/⍵*2)*.5}?
Adám

@ Adám Je n'ai pas beaucoup d'expérience avec APL et la version la plus récente de l'interpréteur GNU (1.7) ne compilera pas sur Mac. Il pourrait donc y avoir certaines limitations. J'essaierai plus tard de voir si ça marche. Merci pour le conseil.
Arc676

Presque toutes les fonctionnalités de GNU APL sont également présentes dans Dyalog APL, disponible gratuitement sur Mac . Vous pouvez également l' essayer en ligne .
Adám

En outre, n'hésitez pas à rejoindre le forum de discussion APL pour en savoir plus.
Adám

2

J , 9 8 octets

-1 merci à mon collègue Marshall.

+&|-|@j.

Essayez-le en ligne!

Prend A comme argument de gauche et B comme argument de droite.

+ la somme

& de

| les magnitudes

- moins

| la magnitude

@ de

j.A + B i

Astuce de golf: combinez les valeurs en un nombre complexe car la diagonale est facile à obtenir, tout en les séparant, car la somme est facile à obtenir.


2

Ajouter ++ , 59 57 octets

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

Essayez-le en ligne!

Cela m'a pris des années à résoudre. Cela n’arrondit pas avec la réponse finale car cela n’est pas possible dans Add ++. Voici comment le programme fonctionne avec les entrées -3et -4( ACCest la valeur de l'accumulateur)

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


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

1
It'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

@EngineerToast, I thought that I had already put up my Google Sheets/ Excel Solutions - thanks for pointing this out
Taylor Scott





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.


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

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

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

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)


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.

En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.