Eingabe in Richtung konvertieren

15

Herausforderung

Bei Eingabe in der Form, <n1>, <n2>in der die Zahl -1, 0 oder 1 sein kann, wird die entsprechende Himmelsrichtung zurückgegeben . Positive Zahlen bewegen sich auf der x-Achse nach Osten und auf der y-Achse nach Süden. Negative Zahlen bewegen sich auf der x-Achse nach Westen und auf der y-Achse nach Norden.

Ausgang muss in Form sein South East, North East, North. Es wird zwischen Groß- und Kleinschreibung unterschieden.

Wenn die Eingabe 0, 0 ist, muss Ihr Programm zurückkehren That goes nowhere, silly!.

Beispiel Input / Outpot:

1, 1 -> South East

0, 1 -> South

1, -1 -> North East

0, 0 -> That goes nowhere, silly!

Dies ist , die kürzeste Antwort in Bytes gewinnt.

Matias K
quelle
Locker verwandt
HyperNeutrino
1
Einige Beispiele mit W, NW und SW werden benötigt.
Seshoumara
@seshoumara Ich bin auf dem Handy, also keine Backticks, aber NW wäre -1, -1
Matias K
1
Sind nachfolgende Leerzeichen erlaubt?
Arjun
Ähh ... Klar, denke ich. Solange es gleich aussieht.
Matias K

Antworten:

12

Japt , 55 51 Bytes

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

Erläuterung

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

Probieren Sie es online!

ETHproductions
quelle
Ähm ... ich ... ??? Wie um alles in der Welt funktioniert das? Hat Japt Lust auf ausgefallene Dinge, die gängige Zeichenpaare ersetzen?
HyperNeutrino
@HyperNeutrino Ja, Japt verwendet die Shoco-Komprimierungsbibliothek, die gängige Paare von Kleinbuchstaben durch ein einzelnes Byte ersetzt.
ETHproductions
Okay, das ist echt cool! Ich werde das untersuchen, um zu sehen, ob ich etwas daraus machen kann.
HyperNeutrino
9

Python 101 87 Bytes

Wirklich naive Lösung.

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

Vielen Dank an @Lynn für das Speichern von 14 Bytes! Änderungen: Mit der string.split-Methode wird es tatsächlich länger; _; Außerdem existieren in Python negative Indizes.

HyperNeutrino
quelle
5
Sie können es so auf 87 reduzieren:lambda x,y:('','South ','North ')[y]+('','East','West')[x]or'That goes nowhere, silly!'
Lynn
2
Ich habe einen guten Weg gefunden, um ein paar Anweisungen zu bekommen, aber leider scheint es nicht so, als würde es für diese Herausforderung funktionieren. Dachte mir, ich würde es trotzdem teilen (vielleicht jemand, der geschickter ist, als ich herausfinden kann, wie man mit seinen Problemen umgeht, wie wenn x oder y = 0): lambda x,y:'North htuoS'[::x][:6]+'EastseW'[::y][:4]Bearbeiten: Es wird wahrscheinlich jetzt zu lang sein, aber Sie können das zweite Schneiden durchführen [:6*x**2]. Ebenso für die Ost / West-Zeichenfolge, wenn Sie den Fehler beim ersten Schneiden umgehen können.
Cole
@Lynn lambda x,y:('North ','South ')[y+1]+('West','East')[x+1]or'That goes nowhere, silly!'ist um 2 Bytes kürzer
Dead Possum
@Lynn Oh, danke! (Ich habe negative Indizes vergessen!)
HyperNeutrino
@DeadPossum Das wird nicht funktionieren , weil sie zurückkehren wird South Eastfür (0, 0). Trotzdem danke!
HyperNeutrino
6

PHP, 101 Bytes

[,$b,$a]=$argv;echo$a|$b?[North,"",South][1+$a]." ".[West,"",East][1+$b]:"That goes nowhere, silly!";
Jörg Hülsermann
quelle
Es ist lange her, dass ich in PHP programmiert habe, aber woher weiß ich, dass Nord, Süd, West und Ost Zeichenfolgen ohne Anführungszeichen sind? Liegt das an der leeren Zeichenfolge, die dasselbe Array verwendet? Wenn ja, bedeutet dies auch, dass Sie nicht gleichzeitig ein Array mit verschiedenen Typen haben können (wie ein Array mit einer Zeichenfolge und einer Ganzzahl)?
Kevin Cruijssen
1
@KevinCruijssen North ist eine Konstante php.net/manual/en/language.constants.php Wenn die Konstante nicht existiert, wird sie als String interpretiert. Ein Array in PHP kann verschiedene Typen enthalten. Zeichenfolgen können auf vier Arten angegeben werden: php.net/manual/en/language.types.string.php
Jörg
6

Perl 6 , 79 Bytes

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

Versuch es

Erweitert:

{ # 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!'
}
Brad Gilbert b2gills
quelle
6

JavaScript (ES6), 106 100 97 93 Byte

Es ist ein sehr einfacher Ansatz. Es besteht aus ein paar ineinander verschachtelten ternären Operatoren -

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

Testfälle

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

Arjun
quelle
a!=0kann durch just ersetzt werden a, da 0 falsch und alle anderen Werte wahr sind. Außerdem ist die Eingabe in der Currying-Syntax kürzer und der Array-Ansatz auch kürzer.
Luke
@ Luke Danke für den Vorschlag! Ich habe die Antwort bearbeitet. Jetzt übertreffe ich die PHP- und Python-Lösungen! Alles wegen dir!!! Vielen Dank!
Arjun
Speichern Sie ein weiteres Byte, indem Sie tun f=a=>b=> und Aufruf der Funktion wie f(1729)(1458); Das ist das currying syntax, was @ Luke erwähnt hat.
Tom
Sie können sicher a|banstelle von verwenden a||b. Angenommen, die Eingabe besteht nur aus -1, 0 oder 1 (was mir unklar ist), könnten Sie a>0und b>0durch ~aund ersetzen ~b.
Arnauld
Außerdem benötigen Sie diese Klammern nicht: a?(...):""/b?(...):""
Arnauld
4

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

Die forSchleife fungiert als Nachschlagetabelle zum Filtern, wenn der (möglicherweise negierte) Parameter gleich -1 ist, und Verketten der übereinstimmenden Wörter. Wenn nichts ausgewählt ist, wird stattdessen die alberne Nachricht gedruckt.

Neil
quelle
4

JavaScript (ES6), 86 Byte

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

Erläuterung

Nennen Sie es mit currying Syntax ( f(a)(b)). Dies verwendet Array-Indizes. Wenn beide aund b0 sind, ist das Ergebnis eine falsch leere Zeichenfolge. In diesem Fall wird die Zeichenfolge nach dem|| zurückgegeben.

Versuch es

Probieren Sie alle Testfälle hier aus:

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

Luke
quelle
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!

Sed führt das Skript standardmäßig so oft aus, wie Eingabezeilen vorhanden sind, sodass bei Bedarf alle Testfälle in einem Durchgang ausgeführt werden können. Der unten stehende TIO-Link macht genau das.

Probieren Sie es online!

Erläuterung:

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

Der verbleibende Musterraum am Ende eines Zyklus wird implizit gedruckt.

Seshoumara
quelle
2

05AB1E , 48 45 43 Bytes

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

Probieren Sie es online!

Erläuterung

õ'†Ô'…´)                                       # 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"
Emigna
quelle
2

Gelee , 40 Bytes

Ṛị"“¡ƘƓ“¡+9“»,“wµ“¡ḳ]“»Kt⁶ȯ“¬ɼ¬<¬O÷ƝḤẎ6»

Probieren Sie es online!

Erik der Outgolfer
quelle
2

Japt , 56 Bytes

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

Probieren Sie es online! |Test Suite

Erläuterung:

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
Oliver
quelle
Hinweis: 00ist genau die gleiche wie 0, wie die zusätzliche Ziffer entfernt wird;)
ETHproductions
1
Die zweitbeste Lösung noch keine Gegenstimme. Ich stimme für dich.
Arjun
1

Retina , 84 82 81 Bytes

1 Byte gespeichert, danke an @seshoumara für den Vorschlag 0...?statt0\w* ?

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

^$
That goes nowhere, silly!

Probieren Sie es online!

Kritixi Lithos
quelle
Die Ausgabe ist falsch. OP will, dass positive Zahlen S auf der y-Achse und negative Zahlen N bewegen.
Seshoumara
@seshoumara Richtig, repariert es für das gleiche bytecount (musste nur tauschen Norund Sou)
Kritixi Lithos
In Ordnung. Sie können auch 1 Byte mit rasieren 0...?.
Seshoumara
@seshoumara Danke für den Tipp :)
Kritixi Lithos
1

Schnelle 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" : ""))}
Stephen
quelle
1

PHP, 95 Bytes.

Dies zeigt einfach das Element des Arrays an, und wenn es nichts gibt, wird einfach die "Standard" -Meldung angezeigt.

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

Dies soll mit der -rFlagge ausgeführt werden und die Koordinaten als erstes und zweites Argument erhalten.

Ismael Miguel
quelle
1

C # , 95 102 Bytes


Golf gespielt

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

Ungolfed lesbar

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

Vollständiger Code

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

Releases

  • v1.1 - + 7 bytes- Wrapped Snippet in eine Funktion.
  • v1.0 -  95 bytes- Anfangslösung.

Anmerkungen

Ich bin ein Geist, Boo!

auhmaan
quelle
1
Das ist ein Code-Snippet, das Sie in eine Funktion (a,b)=>{...}
einschließen
Sie können currying verwenden, um ein Byte zu speichern a=>b=>. Möglicherweise benötigen Sie das ()um das Byte nicht. a|bMöglicherweise können Sie interpolierte Zeichenfolgen verwenden, um den Aufbau der Zeichenfolge zu
verbessern
Völlig vergessen, sich in eine Funktion einzuwickeln: S. Für die ()um die a|bbrauche ich es sonst nicht Operator '|' cannot be applied to operands of type 'int' and 'bool'. Ich habe auch die interpolierten Zeichenfolgen ausprobiert, aber aufgrund der ""Fehler nicht viel gegeben .
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)

Probieren Sie es online aus

Um dies zu verwenden, deklarieren Sie dies als eine Funktion und rufen es auf:

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

Wie es funktioniert

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
corvus_192
quelle
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!");}
Steadybox
quelle
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];}

Erläuterung:

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

Testcode:

Probieren Sie es hier aus.

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

Ausgabe:

South East
South 
North East
That goes nowhere, silly!
Kevin Cruijssen
quelle
0

CJam , 68 Bytes

"
South 
North 

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

Probieren Sie es online! oder überprüfen Sie alle Testfälle

Druckt ein Leerzeichen auf [0 -1]oder[0 1] ( Northoder South).

Erläuterung

"\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!"
Geschäfts-Katze
quelle
0

Röda , 100 Bytes

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

Probieren Sie es online!

Dies ist eine triviale Lösung, ähnlich wie bei einigen anderen Antworten.

fergusq
quelle