입력을 방향으로 변환


15

도전

<n1>, <n2>숫자가 -1, 0 또는 1 일 수있는 형식으로 입력 한 경우 해당 기수 방향을 반환하십시오 . 양수는 x 축에서 동쪽으로, y 축에서 남쪽으로 이동하고, 음수는 x 축에서 서쪽으로, y 축에서 북쪽으로 이동합니다.

출력 양식에 있어야합니다 South East, North East, North. 대소 문자를 구분합니다.

입력이 0, 0이면 프로그램이를 반환해야합니다 That goes nowhere, silly!.

샘플 입력 / 출력 :

1, 1 -> South East

0, 1 -> South

1, -1 -> North East

0, 0 -> That goes nowhere, silly!

이것은 이며, 가장 짧은 대답은 바이트입니다.



1
W, NW 및 SW의 일부 예가 필요합니다.
seshoumara

@seshoumara 저는 모바일에 있습니다. 백틱은 없지만 NW는 -1, -1 일 것입니다
Matias K

1
후행 공백이 허용됩니까?
Arjun

어 ... 그래. 동일하게 보이는 한.
Matias K

답변:


12

apt , 55 51 바이트

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

설명

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

온라인으로 사용해보십시오!


음 ... 나 ... ??? 이 일은 어떻게 작동합니까? Japt는 일반적인 문자 쌍을 대체하는 멋진 것을 좋아합니까?
HyperNeutrino

@HyperNeutrino 예, Japt는 소문자의 일반적인 쌍을 단일 바이트로 바꾸는 shoco 압축 라이브러리 를 사용합니다.
ETHproductions

좋아, 정말 멋지다! 나는 그것을 조사 할 것이고, 그것을 활용할 수 있는지 살펴볼 것이다.
HyperNeutrino

9

파이썬, 101 87 바이트

정말 순진한 솔루션.

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

14 바이트를 절약 한 @Lynn에게 감사합니다! 변경 사항 : string.split 메소드를 사용하면 실제로 더 길어집니다; _; 또한 파이썬에는 음수 색인이 있습니다.


5
다음과 같이 87로 줄일 수 있습니다.lambda x,y:('','South ','North ')[y]+('','East','West')[x]or'That goes nowhere, silly!'
Lynn

2
나는 약간의 지시를받을 수있는 깔끔한 방법을 찾았지만 불행히도이 도전에 효과가없는 것 같습니다. 어쨌든 그것을 공유 할 것이라고 생각했습니다 (아마도 x 또는 y = 0 일 때와 같은 문제를 해결하는 방법을 알아낼 수있는 것보다 더 창의적인 사람) : lambda x,y:'North htuoS'[::x][:6]+'EastseW'[::y][:4]편집 : 이제 너무 길지만 두 번째 슬라이싱을 할 수 있습니다 [:6*x**2]. 첫 번째 슬라이싱에서 오류를 피할 수 있다면 동 / 서 문자열에 대해서도 마찬가지입니다.
Cole

@Lynn lambda x,y:('North ','South ')[y+1]+('West','East')[x+1]or'That goes nowhere, silly!'은 2 바이트 더 짧습니다
Dead Possum

@Lynn 아, 감사합니다! (음수 색인을 잊어 버렸습니다!)
HyperNeutrino

@DeadPossum에 South East대해 반환되므로 작동하지 않습니다 (0, 0). 그래도 감사합니다!
HyperNeutrino

6

PHP, 101 바이트

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

PHP로 프로그래밍한지 오래되었지만, 북쪽, 남쪽, 서쪽 및 동쪽이 큰 따옴표가없는 문자열인지 어떻게 알 수 있습니까? 동일한 배열을 공유하는 빈 문자열 때문입니까? 그렇다면 문자열과 정수가 모두있는 배열과 같이 다른 유형의 배열을 한 번에 가질 수 없다는 의미입니까?
Kevin Cruijssen

1
@KevinCruijssen North는 상수 php.net/manual/en/language.constants.php 상수가 존재하지 않으면 문자열로 해석됩니다. PHP의 배열은 다른 유형을 포함 할 수 있습니다. 문자열은 4 가지 방법으로 지정할 수 있습니다. php.net/manual/en/language.types.string.php
Jörg Hülsermann

6

펄 6 , 79 바이트

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

시도 해봐

넓히는:

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

자바 스크립트 (ES6) 106 100 97 93 바이트

매우 간단한 접근법입니다. 함께 중첩 된 몇 개의 삼항 연산자로 구성됩니다.

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

테스트 사례

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!=0a0은 거짓이고 다른 모든 값은 진실이기 때문에 그냥로 대체 할 수 있습니다 . 또한 커리 구문으로 입력하는 것이 더 짧으며 배열 접근도 더 짧습니다.
Luke

@Luke 제안 해 주셔서 감사합니다! 답변을 편집했습니다. 이제 PHP와 Python 솔루션을 때리고 있습니다! 모든게 너 때문이야!!! 감사!
Arjun

; f=a=>b=>같은 함수 를 수행 하고 호출하여 다른 바이트를 저장하십시오 f(1729)(1458). 이는 인 currying syntax@Luke 언급있다.
Tom

a|b대신에 안전하게 사용할 수 있습니다 a||b. 입력은 -1, 0 또는 1 (나에게 불분명 함)로 구성되어 있다고 가정하면, 당신은 대체 할 수 a>0b>0~a~b.
Arnauld

또한 다음과 같은 괄호가 필요하지 않습니다. a?(...):""/b?(...):""
Arnauld

4

배치, 156 바이트

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

for제 (아마도 부정) 파라미터는 -1과 동일하고 일치하는 단어를 연접 때 루프 필터 룩업 테이블로서 작용한다. 아무것도 선택하지 않으면 바보 같은 메시지가 대신 인쇄됩니다.


4

자바 스크립트 (ES6), 86 바이트

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

설명

카레 구문 ( f(a)(b))으로 호출하십시오 . 배열 인덱스를 사용합니다. 두 경우 a와는 b0이며, 결과는 falsy 빈 문자열입니다. 이 경우 뒤에 문자열 ||이 반환됩니다.

시도 해봐

여기에서 모든 테스트 사례를 시도하십시오.

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 플래그) = 101 바이트

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

의도적으로 sed는 입력 줄이있는 횟수만큼 스크립트를 실행하므로 필요한 경우 한 번의 실행으로 모든 테스트 사례를 수행 할 수 있습니다. 아래의 TIO 링크는 바로 그렇게합니다.

온라인으로 사용해보십시오!

설명:

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

사이클이 끝날 때 남은 패턴 공간이 암시 적으로 인쇄됩니다.


2

05AB1E , 48 45 43 바이트

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

온라인으로 사용해보십시오!

설명

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

apt , 56 바이트

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

온라인으로 사용해보십시오! | 테스트 스위트

설명:

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

힌트 : 00입니다 정확히 같은 0여분의 자리가 제거됩니다대로)
ETHproductions

1
두 번째로 좋은 솔루션은 아직 투표하지 않았습니다. 당신을 위해 찬성했습니다.
Arjun

1

망막 , 84 82 81 바이트

1 바이트는 제안에 대한 @seshoumara에 감사를 저장 0...?하는 대신0\w* ?

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

^$
That goes nowhere, silly!

온라인으로 사용해보십시오!


출력이 잘못되었습니다. OP는 양수는 y 축에서 S를 움직이고 음수는 N을 움직
이기를 원합니다

@seshoumara 맞습니다, 같은 바이트 수로 고쳤습니다. (그냥 교환 Nor하고 Sou)
Kritixi Lithos

확인. 또한를 사용하여 1 바이트를 면도 할 수 있습니다 0...?.
seshoumara

@seshoumara 팁 주셔서 감사합니다 :)
Kritixi Lithos

1

스위프트 151 바이트

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 바이트

이것은 단순히 배열의 요소를 표시하고, 아무것도 없으면 "default"메시지 만 표시합니다.

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

이것은 -r플래그 와 함께 실행되어 코디네이트를 첫 번째 및 두 번째 인수로받습니다.


1

C 번호 , 95 102 바이트


골프

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

언 골프

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

언 골프 가능

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

전체 코드

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

자료

  • V1.1 - + 7 bytes- 함수에 조각을 포장.
  • V1.0 -  95 bytes- 초기 솔루션입니다.

노트

난 유령이야!


1
그것은 코드 스 니펫으로 함수로 감싸 야합니다. 즉 (a,b)=>{...}비트를 추가하십시오
TheLethalCoder

당신은 바이트를 저장하는 무두질 사용할 수있는 a=>b=>필요하지 않을 수도 있습니다, ()주위에를 a|b, 당신은 문자열뿐만 아니라 좋네요을 구축 얻기 위해 보간 문자열을 사용할 수 있습니다
TheLethalCoder

함수로 완전히 감싸는 것을 잊었습니다. : S. 를 들어 ()주위에 a|b, 나는 할 그렇지 않으면이 필요합니다 Operator '|' cannot be applied to operands of type 'int' and 'bool'. 보간 된 문자열도 시도했지만 ""오류가 발생하여 많이주지 않았습니다 .
auhmaan

1

스칼라, 107 바이트

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

온라인으로 사용해보십시오

이것을 사용하려면 이것을 함수로 선언하고 호출하십시오.

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

작동 원리

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 바이트

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

0

자바 7, 130 바이트

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

설명:

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

테스트 코드 :

여기에서 시도하십시오.

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

산출:

South East
South 
North East
That goes nowhere, silly!

0

CJam , 68 바이트

"
South 
North 

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

온라인으로 사용해보십시오! 또는 모든 테스트 사례를 확인

[0 -1]또는 [0 1]( North또는 South) 에 하나의 후행 공백을 인쇄합니다 .

설명

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

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.