Konversi Input ke Arah


15

Tantangan

Masukan yang diberikan dalam bentuk di <n1>, <n2>mana angka bisa -1, 0, atau 1, kembalikan arah mata angin yang sesuai . Bilangan positif bergerak ke Timur di sumbu x dan Selatan di sumbu y, Angka negatif bergerak ke Barat di sumbu x dan Utara di sumbu y.

Output harus dalam bentuk South East, North East, North. Ini case-sensitive.

Jika inputnya 0, 0, program Anda harus kembali That goes nowhere, silly!.

Masukan / Keluaran Sampel:

1, 1 -> South East

0, 1 -> South

1, -1 -> North East

0, 0 -> That goes nowhere, silly!

Ini adalah , jawaban terpendek dalam byte menang.



1
Beberapa contoh dengan W, NW dan SW diperlukan.
seshoumara

@seshoumara Saya menggunakan ponsel, jadi tidak ada backticks, tetapi NW akan menjadi -1, -1
Matias K

1
Apakah Trailing Spaces diizinkan?
Arjun

Uhh ... Tentu, kurasa. Asalkan terlihat sama.
Matias K

Jawaban:


12

Japt , 55 51 byte

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

Penjelasan

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

Cobalah online!


Um ... saya ... ??? Bagaimana cara kerjanya? Apakah Japt menyukai beberapa hal mewah yang menggantikan pasangan karakter umum?
HyperNeutrino

@HyperNeutrino Ya, Japt menggunakan pustaka kompresi shoco yang menggantikan pasangan karakter huruf kecil dengan byte tunggal.
ETHproduk

Oke, itu sangat keren! Saya akan melihat ke dalamnya, melihat apakah saya dapat memanfaatkannya.
HyperNeutrino

9

Python, 101 87 byte

Solusi yang benar-benar naif.

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

Terima kasih kepada @Lynn karena telah menghemat 14 byte! Perubahan: Menggunakan metode string.split sebenarnya membuatnya lebih lama; _; Dan juga, indeks negatif ada di python.


5
Anda dapat memotongnya menjadi 87 seperti ini:lambda x,y:('','South ','North ')[y]+('','East','West')[x]or'That goes nowhere, silly!'
Lynn

2
Saya menemukan cara yang rapi untuk mendapatkan arahan, tapi sayangnya sepertinya itu tidak akan berhasil untuk tantangan ini. Kupikir aku akan membaginya dengan cara apa pun (mungkin seseorang lebih rajin daripada yang bisa kuketahui cara mengatasi masalahnya, seperti ketika x atau y = 0): lambda x,y:'North htuoS'[::x][:6]+'EastseW'[::y][:4]Edit: sepertinya sekarang akan terlalu lama, tetapi Anda dapat membuat irisan kedua [:6*x**2], demikian juga untuk string Timur / Barat, jika Anda dapat menghindari kesalahan pada irisan pertama.
cole

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

@ Lynn Oh, terima kasih! (Saya lupa tentang indeks negatif!)
HyperNeutrino

@DeadPossum Itu tidak akan bekerja karena akan kembali South Eastuntuk (0, 0). Terima kasih!
HyperNeutrino

6

PHP, 101 Bytes

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

Sudah lama sejak saya diprogram dalam PHP, tetapi bagaimana ia tahu Utara, Selatan, Barat dan Timur adalah string tanpa tanda kutip ganda di sekitar mereka? Apakah ini karena String kosong yang berbagi array yang sama? Jika ya, apakah ini juga berarti Anda tidak dapat memiliki array dengan tipe yang berbeda sekaligus (seperti array dengan string dan integer)?
Kevin Cruijssen

1
@KevinCruijssen North adalah konstanta php.net/manual/en/language.constants.php Jika konstanta tidak ada, maka akan ditafsirkan sebagai string. Array dalam PHP dapat berisi berbagai jenis. string dapat ditentukan dalam empat cara php.net/manual/en/language.types.string.php
Jörg Hülsermann

6

Perl 6, 79 bytes

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

Try it

Diperluas:

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

It's a very simple approach. It consists of a few ternary operators nested together -

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

Test Cases

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!=0 can be replaced by just a, since 0 is falsy and all other values are truthy. Also, taking input in currying syntax is shorter, and the array appoach is also shorter.
Luke

@Luke Thanks for the suggestion! I have edited the answer. Now, I am beating the PHP and Python solutions! All because of you!!! Thanks!
Arjun

Save another byte by doing f=a=>b=> and calling the function like f(1729)(1458); which is the currying syntax that @Luke mentioned.
Tom

You can safely use a|b instead of a||b. Assuming that the input only consists of -1, 0 or 1 (which is unclear to me), you could replace a>0 and b>0 with ~a and ~b.
Arnauld

Also, you don't need these parentheses: 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%

The for loop acts as a lookup table to filter when the (possibly negated) parameter equals -1, and concatenating the matching words. If nothing is selected then the silly message is printed instead.


4

JavaScript (ES6), 86 bytes

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

Explanation

Call it with currying syntax (f(a)(b)). This uses array indices. If both a and b are 0, the result is a falsy empty string. In that case, the string after the || is returned.

Try it

Try all test cases here:

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!

By design, sed executes the script as many times as there are input lines, so one can do all the test cases in one run, if needed. The TIO link below does just that.

Try it online!

Explanation:

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

The remaining pattern space at the end of a cycle is printed implicitly.


2

05AB1E, 48 45 43 bytes

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

Try it online!

Explanation

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

Try it online! | Test Suite

Explanation:

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

Hint: 00 is exactly the same as 0, as the extra digit gets removed ;)
ETHproductions

1
The second-best solution yet no upvote. I upvote for you.
Arjun

1

Retina, 84 82 81 bytes

1 byte saved thanks to @seshoumara for suggesting 0...? instead of 0\w* ?

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

^$
That goes nowhere, silly!

Try it online!


The output is wrong. OP wants positive numbers to move S in the y-axis and negative numbers to move N.
seshoumara

@seshoumara Right, fixed it for same bytecount (just had to swap Nor and Sou)
Kritixi Lithos

Ok. Also, you can shave 1 byte by using 0...?.
seshoumara

@seshoumara Thanks for the tip :)
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.

This simply displays the element of the array, and if there's nothing, just displays the "default" message.

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

This is meant to run with the -r flag, receiving the coordenates as the 1st and 2nd arguments.


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

Ungolfed

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

Ungolfed readable

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

Full 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 into a function.
  • v1.0 -  95 bytes - Initial solution.

Notes

I'm a ghost, boo!


1
That's a code snippet you need to wrap it in a function i.e. add the (a,b)=>{...} bit
TheLethalCoder

You can use currying to save a byte a=>b=>, might not need the () around the a|b, you might be able to use interpolated strings to get the string built up nicer as well
TheLethalCoder

Completely forgot to wrap into a function :S. For the () around the a|b, I do need it, otherwise Operator '|' cannot be applied to operands of type 'int' and 'bool'. I've also tried the interpolated strings, but didn't give much though due to the "" giving me errors.
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)

Try it online

To use this, declare this as a function and call it:

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

How it works

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

Explanation:

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

Test code:

Try it here.

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

Output:

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!"?

Try it online! or verify all test cases

Prints one trailing space on [0 -1] or [0 1] (North or South).

Explanation

"\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]]}

Try it online!

This is a trivial solution, similar to some other answers.

Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.