将输入转换为方向


15

挑战

<n1>, <n2>number可以为-1、0或1 的形式给定输入,返回相应的基本方向。正数在x轴上向东移动,y轴上向南移动,负数在x轴上向西移动,y轴上向北移动。

输出必须在形式South EastNorth EastNorth。区分大小写。

如果输入为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'Mar

Answers:


12

Japt55 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!'

感谢@Lynn节省了14个字节!更改:使用string.split方法实际上会使它更长;而且,python中存在负索引。


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

@琳恩哦,谢谢!(我忘记了负索引!)
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编程以来已经有很长时间了,但是如何知道北,南,西和东是没有双引号的字符串呢?这是因为共享相同数组的空String吗?如果是,这是否还意味着您不能一次拥有一个具有不同类型的数组(例如同时包含字符串和整数的数组)?
凯文·克鲁伊森

1
@KevinCruijssen North是一个常量php.net/manual/en/language.constants.php如果该常量不存在,它将被解释为字符串。PHP中的数组可以包含不同的类型。字符串可以用四种方法来指定php.net/manual/en/language.types.string.php
约尔格Hülsermann

6

Perl 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

JavaScript(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!=0可以用just代替a,因为0是伪造的,而其他所有值都是真。同样,采用currying语法的输入更短,并且数组处理也更短。
路加福音

@Luke感谢您的建议!我已经编辑了答案。现在,我击败了PHP和Python解决方案!都是因为你!谢谢!
Arjun

通过执行f=a=>b=>和调用类似函数来节省另一个字节f(1729)(1458);这是currying syntax该@Luke提及。
汤姆,

您可以放心使用a|b来代替a||b。假设输入仅包含-1、0或1(我不清楚),则可以将a>0and 替换b>0~aand ~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

JavaScript(ES6),86个字节

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

说明

使用currying语法(f(a)(b))进行调用。这使用数组索引。如果ab均为0,则结果为虚假的空字符串。在这种情况下,||返回。

尝试一下

在这里尝试所有测试用例:

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

05AB1E48 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

Japt 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字节

感谢@seshoumara节省了1个字节,0...?而不是建议0\w* ?

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

^$
That goes nowhere, silly!

在线尝试!


输出错误。OP希望正数移动S沿y轴和负数移动N.
seshoumara

@seshoumara对,将其修复为相同的字节数(只需要交换NorSou
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个字节。

这仅显示数组的元素,如果没有任何内容,则仅显示“默认”消息。

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 -裹片段注入的功能。
  • 1.0 - 95 bytes -初始溶液。

笔记

我是鬼,嘘!


1
这是一个代码片段,您需要将其包装在一个函数中,即添加该(a,b)=>{...}
TheLethalCoder

您可以使用currying保存一个字节a=>b=>,可能不需要()周围的内容a|b,也可以使用内插的字符串来使字符串更好地建立起来
TheLethalCoder

完全忘了换成一个功能:S。对于()周围的a|b,我确实需要它,否则Operator '|' cannot be applied to operands of type 'int' and 'bool'。我也尝试过内插的字符串,但是由于""给我错误而没有给出太多。
auhmaan

1

Scala,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

Java 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]NorthSouth)上打印一个尾随空格。

说明

"\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字节

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

在线尝试!

这是一个简单的解决方案,类似于其他一些答案。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.