Convertir entrada a dirección


15

Desafío

Dada la entrada en la forma <n1>, <n2>en que el número puede ser -1, 0 o 1, devuelve la dirección cardinal correspondiente . Los números positivos se mueven hacia el este en el eje xy hacia el sur en el eje y, los números negativos se mueven hacia el oeste en el eje xy hacia el norte en el eje y.

Salida debe ser en forma South East, North East, North. Es sensible a mayúsculas y minúsculas.

Si la entrada es 0, 0, su programa debe regresar That goes nowhere, silly!.

Entrada / muestra de muestra:

1, 1 -> South East

0, 1 -> South

1, -1 -> North East

0, 0 -> That goes nowhere, silly!

Este es el , gana la respuesta más corta en bytes.



1
Se necesitan algunos ejemplos con W, NW y SW.
seshoumara

@seshoumara Estoy en el móvil, así que no hay retrocesos, pero NW sería -1, -1
Matias K

1
¿Se permiten espacios finales?
Arjun

Uhh ... Claro, supongo. Mientras se vea igual.
Matias K

Respuestas:


12

Japt , 55 51 bytes

`
SÆ 
Nư `·gV +`
E†t
Wƒt`·gU ª`T•t goƒ Í2€e, Ðéy!

Explicación

                      // Implicit: U, V = inputs
`\nSÆ \nNư `       // Take the string "\nSouth \nNorth ".
·                     // Split it at newlines, giving ["", "South ", "North "].
gV                    // Get the item at index V. -1 corresponds to the last item.
+                     // Concatenate this with
`\nE†t\nWƒt`·gU       // the item at index U in ["", "East", "West"].
ª`T•t goƒ Í2€e, Ðéy!  // If the result is empty, instead take "That goes nowhere, silly!".
                      // Implicit: output result of last expression

Pruébalo en línea!


Um ... yo ... ??? ¿Cómo diablos funciona esto? ¿Tiene Japt algunas cosas elegantes que reemplazan a los pares de caracteres comunes?
HyperNeutrino

@HyperNeutrino Sí, Japt usa la biblioteca de compresión shoco que reemplaza los pares comunes de caracteres en minúsculas con un solo byte.
ETHproductions

Ok, eso es realmente genial! Investigaré eso, veré si puedo usarlo.
HyperNeutrino

9

Python, 101 87 bytes

Solución realmente ingenua.

lambda x,y:['','South ','North '][y]+['','West','East'][x]or'That goes nowhere, silly!'

¡Gracias a @Lynn por guardar 14 bytes! Cambios: el uso del método string.split en realidad lo hace más largo; _; Y también, existen índices negativos en python.


55
Puede reducirlo a 87 así:lambda x,y:('','South ','North ')[y]+('','East','West')[x]or'That goes nowhere, silly!'
Lynn

2
Encontré una buena manera de obtener algunas instrucciones, pero desafortunadamente no parece que funcione para este desafío. Pensé que lo compartiría de todos modos (tal vez alguien más hábil que yo pueda descubrir cómo lidiar con sus problemas, como cuando x o y = 0): lambda x,y:'North htuoS'[::x][:6]+'EastseW'[::y][:4]Editar: es probable que ahora sea demasiado largo, pero puedes hacer el segundo corte [:6*x**2], del mismo modo para la cadena Este / Oeste, si puede evitar el error en el primer corte.
cole

@Lynn lambda x,y:('North ','South ')[y+1]+('West','East')[x+1]or'That goes nowhere, silly!'es más corto en 2 bytes
Dead Possum

@ Lynn ¡Oh, gracias! (¡Olvidé los índices negativos!)
HyperNeutrino

@DeadPossum Eso no funcionará porque regresará South Eastpor (0, 0). ¡Gracias de cualquier forma!
HyperNeutrino

6

PHP, 101 bytes

[,$b,$a]=$argv;echo$a|$b?[North,"",South][1+$a]." ".[West,"",East][1+$b]:"That goes nowhere, silly!";

Ha pasado mucho tiempo desde que programé en PHP, pero ¿cómo sabe que Norte, Sur, Oeste y Este son cadenas sin comillas dobles a su alrededor? ¿Esto se debe a la cadena vacía que comparte la misma matriz? En caso afirmativo, ¿esto también significa que no puede tener una matriz con diferentes tipos a la vez (como una matriz con una cadena y un entero)?
Kevin Cruijssen

1
@KevinCruijssen North es una constante php.net/manual/en/language.constants.php Si la constante no existe, se interpretará como una cadena. Una matriz en PHP puede contener diferentes tipos. las cadenas se pueden especificar de cuatro maneras php.net/manual/en/language.types.string.php
Jörg Hülsermann el

6

Perl 6 , 79 bytes

{<<'' East South North West>>[$^y*2%5,$^x%5].trim||'That goes nowhere, silly!'}

Intentalo

Expandido:

{ # bare block lambda with placeholder parameters 「$x」 and 「$y」

  << '' East South North West >>\ # list of 5 strings
  [                               # index into that with:

    # use a calculation so that the results only match on 0
    $^y * 2 % 5, # (-1,0,1) => (3,0,2) # second parameter
    $^x % 5      # (-1,0,1) => (4,0,1) # first parameter

  ]
  .trim  # turn that list into a space separated string implicitly
         # and remove leading and trailing whitespace

  ||     # if that string is empty, use this instead
  'That goes nowhere, silly!'
}

6

JavaScript (ES6), 106 100 97 93 bytes

Es un enfoque muy simple. Consiste en unos pocos operadores ternarios anidados juntos:

f=a=>b=>a|b?(a?a>0?"South ":"North ":"")+(b?b>0?"East":"West":""):"That goes nowhere, silly!"

Casos de prueba

f=a=>b=>a|b?(a?a>0?"South ":"North ":"")+(b?b>0?"East":"West":""):"That goes nowhere, silly!"

console.log(f(1729)(1458));
console.log(f(1729)(-1458));
console.log(f(-1729)(1458));
console.log(f(-1729)(-1458));
console.log(f(0)(1729));
console.log(f(0)(-1729));
console.log(f(1729)(0));
console.log(f(-1729)(0));


a!=0puede reemplazarse por just a, ya que 0 es falso y todos los demás valores son verdaderos. Además, tomar la entrada en la sintaxis de curry es más corto, y el enfoque de matriz también es más corto.
Lucas

@Luke Gracias por la sugerencia! He editado la respuesta. ¡Ahora estoy superando las soluciones PHP y Python! ¡¡¡Todo por ti!!! ¡Gracias!
Arjun

Guarde otro byte haciendo f=a=>b=>y llamando a la función como f(1729)(1458); que es lo currying syntaxque mencionó @Luke.
Tom

Puede usar de forma segura en a|blugar de a||b. Suponiendo que la entrada solo consta de -1, 0 o 1 (que no está claro para mí), podría reemplazar a>0y b>0con ~ay ~b.
Arnauld

Además, no necesita estos paréntesis: a?(...):""/b?(...):""
Arnauld

4

Lote, 156 bytes

@set s=
@for %%w in (North.%2 South.-%2 West.%1 East.-%1)do @if %%~xw==.-1 call set s=%%s%% %%~nw
@if "%s%"=="" set s= That goes nowhere, silly!
@echo%s%

El forbucle actúa como una tabla de búsqueda para filtrar cuando el parámetro (posiblemente negado) es igual a -1 y concatena las palabras coincidentes. Si no se selecciona nada, se imprime el mensaje tonto.


4

JavaScript (ES6), 86 bytes

a=>b=>["North ","","South "][b+1]+["West","","East"][a+1]||"That goes nowhere, silly!"

Explicación

Llámalo con sintaxis curry ( f(a)(b)). Esto usa índices de matriz. Si ambos ayb son 0, el resultado es una cadena vacía falsa. En ese caso, la cadena después de la|| se devuelve .

Intentalo

Pruebe todos los casos de prueba aquí:

let f=
a=>b=>["North ","","South "][b+1]+["West","","East"][a+1]||"That goes nowhere, silly!"

for (let i = -1; i < 2; i++) {
    for (let j = -1; j < 2; j++) {
        console.log(`${i}, ${j}: ${f(i)(j)}`);
    }
}


3

GNU sed , 100 + 1 (r flag) = 101 bytes

s:^-1:We:
s:^1:Ea:
s:-1:Nor:
s:1:Sou:
s:(.*),(.*):\2th \1st:
s:0...?::
/0/cThat goes nowhere, silly!

Por diseño, sed ejecuta el script tantas veces como haya líneas de entrada, por lo que uno puede hacer todos los casos de prueba en una ejecución, si es necesario. El siguiente enlace de TIO hace exactamente eso.

Pruébalo en línea!

Explicación:

s:^-1:We:                         # replace '-1' (n1) to 'We'
s:^1:Ea:                          # replace '1' (n1) to 'Ea'
s:-1:Nor:                         # replace '-1' (n2) to 'Nor'
s:1:Sou:                          # replace '1' (n2) to 'Sou'
s:(.*),(.*):\2th \1st:            # swap the two fields, add corresponding suffixes
s:0...?::                         # delete first field found that starts with '0'
/0/cThat goes nowhere, silly!     # if another field is found starting with '0',
                                  #print that text, delete pattern, end cycle now

El espacio de patrón restante al final de un ciclo se imprime implícitamente.


2

05AB1E , 48 45 43 bytes

õ'†Ô'…´)èUõ„ƒÞ „„¡ )èXJ™Dg_i“§µ—±æÙ,Ú¿!“'Tì

Pruébalo en línea!

Explicación

õ'†Ô'…´)                                       # push the list ['','east','west']
        èU                                     # index into this with first input
                                               # and store the result in X
          õ„ƒÞ „„¡ )                           # push the list ['','south ','north ']
                    èXJ                        # index into this with 2nd input
                                               # and join with the content of X
                       ™                       # convert to title-case
                        Dg_i                   # if the length is 0
                            “§µ—±æÙ,Ú¿!“       # push the string "hat goes nowhere, silly!"
                                        'Tì    # prepend "T"


2

Japt , 56 bytes

N¬¥0?`T•t goƒ Í2€e, Ðéy!`:` SÆ Nư`¸gV +S+` E†t Wƒt`¸gU

Pruébalo en línea! El | Banco de pruebas

Explicación:

N¬¥0?`Tt go Í2e, Ðéy!`:` SÆ Nư`¸gV +S+` Et Wt`¸gU
Implicit U = First input
         V = Second input

N´0?`...`:` ...`qS gV +S+` ...`qS gU
N¬                                                     Join the input (0,0 → "00")
  ¥0                                                   check if input is roughly equal to 0. In JS, "00" == 0
    ?                                                  If yes:
      ...                                               Output "That goes nowhere, silly!". This is a compressed string
     `   `                                              Backticks are used to decompress strings
          :                                            Else:
           ` ...`                                       " South North" compressed
                 qS                                     Split on " " (" South North" → ["","South","North"])
                   gV                                   Return the string at index V
                     +S+                                +" "+ 
                        ` ...`                          " East West" compressed
                              qS gU                     Split on spaces and yield string at index U

Sugerencia: 00es exactamente lo mismo 0, ya que se elimina el dígito adicional;)
ETHproductions

1
La segunda mejor solución pero sin voto positivo. Voto por ti.
Arjun

1

Retina , 84 82 81 bytes

1 byte guardado gracias a @seshoumara por sugerir en 0...?lugar de0\w* ?

(.+) (.+)
$2th $1st
^-1
Nor
^1
Sou
-1
We
1
Ea
0...?

^$
That goes nowhere, silly!

Pruébalo en línea!


La salida es incorrecta. OP quiere que los números positivos muevan S en el eje yy los números negativos que muevan N.
seshoumara

@seshoumara Derecha, lo arreglé para el mismo bytecount (solo tuve que cambiar Nory Sou)
Kritixi Lithos

Okay. Además, puede afeitarse 1 byte usando 0...?.
seshoumara

@seshoumara Gracias por el consejo :)
Kritixi Lithos

1

Swift 151 bytes

func d(x:Int,y:Int){x==0&&y==0 ? print("That goes nowhere, silly!") : print((y<0 ? "North " : y>0 ? "South " : "")+(x<0 ? "West" : x>0 ? "East" : ""))}

1

PHP, 95 bytes.

Esto simplemente muestra el elemento de la matriz y, si no hay nada, solo muestra el mensaje "predeterminado".

echo['North ','','South '][$argv[1]+1].[East,'',West][$argv[2]+1]?:'That goes nowhere, silly!';

Está destinado a ejecutarse con la -rbandera, recibiendo las coordenadas como los argumentos primero y segundo.


1

C # , 95 102 bytes


Golfed

(a,b)=>(a|b)==0?"That goes nowhere, silly!":(b<0?"North ":b>0?"South ":"")+(a<0?"West":a>0?"East":"");

Sin golf

( a, b ) => ( a | b ) == 0
    ? "That goes nowhere, silly!"
    : ( b < 0 ? "North " : b > 0 ? "South " : "" ) +
      ( a < 0 ? "West" : a > 0 ? "East" : "" );

Legible sin golf

// A bitwise OR is perfomed
( a, b ) => ( a | b ) == 0

    // If the result is 0, then the 0,0 text is returned
    ? "That goes nowhere, silly!"

    // Otherwise, checks against 'a' and 'b' to decide the cardinal direction.
    : ( b < 0 ? "North " : b > 0 ? "South " : "" ) +
      ( a < 0 ? "West" : a > 0 ? "East" : "" );

Código completo

using System;

namespace Namespace {
    class Program {
        static void Main( string[] args ) {
            Func<Int32, Int32, String> f = ( a, b ) =>
                ( a | b ) == 0
                    ? "That goes nowhere, silly!"
                    : ( b < 0 ? "North " : b > 0 ? "South " : "" ) +
                      ( a < 0 ? "West" : a > 0 ? "East" : "" );

            for( Int32 a = -1; a <= 1; a++ ) {
                for( Int32 b = -1; b <= 1; b++ ) {
                    Console.WriteLine( $"{a}, {b} = {f( a, b )}" );
                }
            }

            Console.ReadLine();
        }
    }
}

Lanzamientos

  • v1.1 - + 7 bytes- Fragmento envuelto en una función.
  • v1.0 -  95 bytes- Solución inicial.

Notas

Soy un fantasma, boo!


1
Ese es un fragmento de código que necesita para envolverlo en una función, es decir, agregar el (a,b)=>{...}bit
TheLethalCoder

Se puede utilizar para guardar currying un byte a=>b=>, podría no necesitar la ()vuelta de la a|b, es posible que pueda utilizar cadenas interpolados para obtener la cadena construye más bonito así
TheLethalCoder

Se olvidó completamente de envolver en una función: S. Para ()todo el mundo a|b, lo necesito, de lo contrario Operator '|' cannot be applied to operands of type 'int' and 'bool'. También probé las cadenas interpoladas, pero no di mucho debido a ""que me dieron errores.
auhmaan

1

Scala, 107 bytes

a=>b=>if((a|b)==0)"That goes nowhere, silly!"else Seq("North ","","South ")(b+1)+Seq("West","","East")(a+1)

Pruébalo en línea

Para usar esto, declare esto como una función y llámelo:

val f:(Int=>Int=>String)=...
println(f(0)(0))

Cómo funciona

a =>                                // create an lambda with a parameter a that returns
  b =>                              // a lambda with a parameter b
    if ( (a | b) == 0)                // if a and b are both 0
      "That goes nowhere, silly!"       // return this string
    else                              // else return
      Seq("North ","","South ")(b+1)    // index into this sequence
      +                                 // concat
      Seq("West","","East")(a+1)        // index into this sequence

1

C, 103 bytes

f(a,b){printf("%s%s",b?b+1?"South ":"North ":"",a?a+1?"East":"West":b?"":"That goes nowhere, silly!");}

0

Java 7, 130 bytes

String c(int x,int y){return x==0&y==0?"That goes nowhere, silly!":"North xxSouth ".split("x")[y+1]+"WestxxEast".split("x")[x+1];}

Explicación:

String c(int x, int y){               // Method with x and y integer parameters and String return-type
  return x==0&y==0 ?                  //  If both x and y are 0:
     "That goes nowhere, silly!"      //   Return "That goes nowhere, silly!"
    :                                 //  Else:
     "North xxSouth ".split("x"[y+1]  //   Get index y+1 from array ["North ","","South "] (0-indexed)
     + "WestxxEast".split("x")[x+1];  //   Plus index x+1 from array ["West","","East"] (0-indexed)
}                                     // End of method

Código de prueba:

Pruébalo aquí.

class M{
  static String c(int x,int y){return x==0&y==0?"That goes nowhere, silly!":"North xxSouth ".split("x")[y+1]+"WestxxEast".split("x")[x+1];}

  public static void main(String[] a){
    System.out.println(c(1, 1));
    System.out.println(c(0, 1));
    System.out.println(c(1, -1));
    System.out.println(c(0, 0));
  }
}

Salida:

South East
South 
North East
That goes nowhere, silly!

0

CJam , 68 bytes

"
South 
North 

East
West"N/3/l~W%.=s_Q"That goes nowhere, silly!"?

Pruébalo en línea! o verificar todos los casos de prueba

Imprime un espacio final en [0 -1]o [0 1]( Northo South).

Explicación

"\nSouth \nNorth \n\nEast\nWest"  e# Push this string
N/                                e# Split it by newlines
3/                                e# Split the result into 3-length subarrays,
                                  e#  gives [["" "South " "North "]["" "East" "West"]]
l~                                e# Read and eval a line of input
W%                                e# Reverse the co-ordinates
.=                                e# Vectorized get-element-at-index: accesses the element
                                  e#  from the first array at the index given by the 
                                  e#  y co-ordinate. Arrays are modular, so -1 is the last
                                  e#  element. Does the same with x on the other array.
s                                 e# Cast to string (joins the array with no separator)
_                                 e# Duplicate the string
Q"That goes nowhere, silly!"?     e# If it's non-empty, push an empty string. If its empty, 
                                  e#  push "That goes nowhere, silly!"

0

Röda , 100 bytes

f a,b{["That goes nowhere, silly!"]if[a=b,a=0]else[["","South ","North "][b],["","East","West"][a]]}

Pruébalo en línea!

Esta es una solución trivial, similar a algunas otras respuestas.

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.