Converti input in direzione


15

Sfida

Dato input nella forma in <n1>, <n2>cui il numero può essere -1, 0 o 1, restituisce la direzione cardinale corrispondente . I numeri positivi si spostano verso est nell'asse xe verso sud nell'asse y, i numeri negativi si spostano verso ovest nell'asse xe verso nord nell'asse y.

Uscita deve essere in forma South East, North East, North. Fa distinzione tra maiuscole e minuscole.

Se l'ingresso è 0, 0, il programma deve tornare That goes nowhere, silly!.

Esempio di input / outpot:

1, 1 -> South East

0, 1 -> South

1, -1 -> North East

0, 0 -> That goes nowhere, silly!

Questo è , vince la risposta più breve in byte.



1
Sono necessari alcuni esempi con W, NW e SW.
seshoumara,

@seshoumara Sono su cellulare, quindi nessun backtick, ma NW sarebbe -1, -1
Matias K

1
Gli spazi finali sono consentiti?
Arjun,

Uhh ... Certo, immagino. Finché sembra lo stesso.
Matias K

Risposte:


12

Japt , 55 51 byte

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

Spiegazione

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

Provalo online!


Ehm ... io ... ??? Come mai funziona? Japt ha cose fantasiose che sostituiscono le coppie di personaggi comuni?
HyperNeutrino,

@HyperNeutrino Sì, Japt utilizza la libreria di compressione shoco che sostituisce le coppie comuni di caratteri minuscoli con un singolo byte.
ETHproductions

Va bene, è davvero fantastico! Lo esaminerò, vedrò se ne posso fare uso.
HyperNeutrino,

9

Python, 101 87 byte

Soluzione davvero ingenua.

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

Grazie a @Lynn per aver salvato 14 byte! Modifiche: l'utilizzo del metodo string.split in realtà lo rende più lungo; _; Inoltre, in Python esistono indici negativi.


5
Puoi ridurlo a 87 in questo modo:lambda x,y:('','South ','North ')[y]+('','East','West')[x]or'That goes nowhere, silly!'
Lynn

2
Ho trovato un modo pulito per ottenere alcune indicazioni, ma sfortunatamente non sembra funzionare per questa sfida. Ho pensato che l'avrei condiviso comunque (forse qualcuno più furbo di quanto riesca a capire come affrontare i suoi problemi, come quando x o y = 0): lambda x,y:'North htuoS'[::x][:6]+'EastseW'[::y][:4]Modifica: probabilmente ora sarà troppo lungo, ma puoi fare la seconda suddivisione [:6*x**2], allo stesso modo per la stringa est / ovest, se è possibile aggirare l'errore al primo taglio.
Cole

@Lynn lambda x,y:('North ','South ')[y+1]+('West','East')[x+1]or'That goes nowhere, silly!'è più corto di 2 byte
Dead Possum

@Lynn Oh, grazie! (Ho dimenticato gli indici negativi!)
HyperNeutrino

@DeadPossum Non funzionerà perché tornerà South Eastper (0, 0). Grazie comunque!
HyperNeutrino

6

PHP, 101 byte

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

È da tanto che non ho programmato in PHP, ma come fa a sapere che Nord, Sud, Ovest e Est sono stringhe senza virgolette? È a causa della stringa vuota che condivide lo stesso array? Se sì, significa anche che non puoi avere un array con tipi diversi contemporaneamente (come un array con una stringa e un numero intero)?
Kevin Cruijssen,

1
@KevinCruijssen North è una costante php.net/manual/en/language.constants.php Se la costante non esiste verrà interpretata come stringa. Un array in PHP può contenere diversi tipi. stringhe possono essere specificate in quattro modi php.net/manual/en/language.types.string.php
Jörg Hülsermann

6

Perl 6 , 79 byte

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

Provalo

Allargato:

{ # 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 byte

È un approccio molto semplice. Consiste in alcuni operatori ternari nidificati insieme -

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

Casi test

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!=0può essere sostituito da just a, poiché 0 è falsy e tutti gli altri valori sono true. Inoltre, accettare input nella sintassi del curry è più breve e anche l'approccio dell'array è più breve.
Luca

@Luke Grazie per il suggerimento! Ho modificato la risposta. Ora sto battendo le soluzioni PHP e Python! Tutto per colpa tua!!! Grazie!
Arjun,

Salvare un altro byte eseguendo f=a=>b=>e chiamando la funzione like f(1729)(1458); che è quello currying syntaxche ha menzionato @Luke.
Tom

Puoi usare tranquillamente a|binvece di a||b. Supponendo che l'input sia costituito solo da -1, 0 o 1 (che per me non è chiaro), è possibile sostituire a>0e b>0con ~ae ~b.
Arnauld,

Inoltre, non hai bisogno di queste parentesi: a?(...):""/b?(...):""
Arnauld

4

Lotto, 156 byte

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

Il forciclo funge da tabella di ricerca per filtrare quando il parametro (eventualmente negato) è uguale a -1 e concatenare le parole corrispondenti. Se non viene selezionato nulla, viene invece stampato il messaggio sciocco.


4

JavaScript (ES6), 86 byte

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

Spiegazione

Chiamalo con la sintassi del curry ( f(a)(b)). Questo utilizza indici di array. Se entrambi ae bsono 0, il risultato è una stringa vuota falsa. In tal caso, ||viene restituita la stringa dopo il .

Provalo

Prova tutti i casi di test qui:

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 (flag r) = 101 byte

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

In base alla progettazione, sed esegue lo script tutte le volte che sono presenti righe di input, quindi è possibile eseguire tutti i casi di test in un'unica esecuzione, se necessario. Il link TIO qui sotto fa proprio questo.

Provalo online!

Spiegazione:

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

Lo spazio del motivo rimanente alla fine di un ciclo viene stampato implicitamente.


2

05AB1E , 48 45 43 byte

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

Provalo online!

Spiegazione

õ'†Ô'…´)                                       # 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 byte

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

Provalo online! | Test Suite

Spiegazione:

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

Suggerimento: 00è esattamente lo stesso di quando 0viene rimossa la cifra aggiuntiva;)
ETHproductions

1
La seconda soluzione migliore ma senza voti positivi. Ho votato per te.
Arjun,

1

Retina , 84 82 81 byte

1 byte salvato grazie a @seshoumara per aver suggerito 0...?invece di0\w* ?

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

^$
That goes nowhere, silly!

Provalo online!


L'output è sbagliato. OP vuole che i numeri positivi spostino S nell'asse y e i numeri negativi spostino N.
seshoumara

@seshoumara Right, risolto per lo stesso bytecount (dovevo solo scambiare Nore Sou)
Kritixi Lithos

Ok. Inoltre, puoi radere 1 byte usando 0...?.
seshoumara,

@seshoumara Grazie per la punta :)
Kritixi Lithos

1

Swift 151 byte

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

Questo visualizza semplicemente l'elemento dell'array e, se non c'è nulla, visualizza semplicemente il messaggio "predefinito".

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

Questo è pensato per correre con la -rbandiera, ricevendo i coordinati come 1 ° e 2 ° argomento.


1

C # , 95 102 byte


golfed

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

Ungolfed

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

Leggibile non golfato

// 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" : "" );

Codice 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();
        }
    }
}

Uscite

  • v1.1 - + 7 bytes- Snippet avvolto in una funzione.
  • v1.0 -  95 bytes- Soluzione iniziale.

Appunti

Sono un fantasma, amico!


1
Questo è uno snippet di codice che devi racchiudere in una funzione, cioè aggiungere il (a,b)=>{...}bit
TheLethalCoder

Puoi usare il curry per salvare un byte a=>b=>, potresti non aver bisogno del ()around a|b, potresti essere in grado di usare stringhe interpolate per rendere la stringa più carina
TheLethalCoder

Dimenticato completamente di concludere una funzione: S. Per il ()intorno a|b, ne ho bisogno, altrimenti Operator '|' cannot be applied to operands of type 'int' and 'bool'. Ho anche provato le stringhe interpolate, ma non mi ha dato molto a causa dei ""miei errori.
auhmaan,

1

Scala, 107 byte

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

Provalo online

Per usarlo, dichiaralo come una funzione e chiamalo:

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

Come funziona

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 byte

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 byte

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];}

Spiegazione:

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

Codice di prova:

Provalo qui.

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

Produzione:

South East
South 
North East
That goes nowhere, silly!

0

CJam , 68 byte

"
South 
North 

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

Provalo online! o verifica tutti i casi di test

Stampa uno spazio finale su [0 -1]o [0 1]( Northo South).

Spiegazione

"\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 byte

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

Provalo online!

Questa è una soluzione banale, simile ad alcune altre risposte.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.