优先权


12

您的任务是调节十字路口的交通。北,东,南和西有4条道路。

输入是一个字符串,代表每条道路上即将到来的交通。例如,NNNWS表示总共有5辆车:北三辆,西三辆,南三辆。字符的顺序在这里不重要,NNNWS等效于WNNSN

您必须使用正确规则的优先级来输出小汽车行驶的顺序:从南方来的汽车必须先让从东方来的汽车先行,向东让北,向北让西,向西让路南。

例如,在输入的情况下NNNWS,应该先向南行驶,然后向西行驶,再向北行驶3辆。因此,输出应为SWNNN

存在一些不确定的情况,例如:NSNNWSE:然后应输出string stuck

测试用例

N => N
NW => WN
NWS => SWN
SNW => SWN
SSSSS => SSSSS
ENNNNES => NNNNEES
NS => stuck
NNWSE => stuck

3
这两个似乎都很难,因为它们也考虑了传出的方向。
Martin Ender

3
我建议使用未定义的行为,而不是打印stuck
Erik the Outgolfer

4
@Erik处理道路安全时,无法接受未定义的行为:-)
Arnaud


2
空字符串可以作为输入吗?如果是这样,结果应该是什么?为什么会NS卡住?因为这两个NSSN将是一个解决方案吗?
Ton Hospel '16

Answers:


2

Perl,65个字节

包括+2 -lp

在STDIN上输入。假定空字符串不是有效输入

#!/usr/bin/perl -lp
s%.%'+(y/NESW/ESWN/*s/N(.*)W/W$1N/,/N/^/S/)'x4%gere+0or$_=stuck

如果您不介意没有换行符,stuck可以删除该l选项


2

PHP,267字节

使用新的飞船操作人员usort -5字节由@IsmaelMiguel

<?foreach($f=[E,S,W,N]as$l)$s.=+!($r=strstr)($i=$argv[1],$l);if(in_array($s,[0101,1010,0000]))die(stuck);$x=($p=strpos)($s,"1");$t=$r($j=join($f),$f[$x]).$r($j,$f[$x],1);$a=str_split($i);usort($a,function($x,$y)use($t,$p){return$p($t,$x)<=>$p($t,$y);});echo join($a);

分解

# Extended Version without notices
$s="";
foreach($f=["E","S","W","N"] as $l){$s.=+!strstr($i=$argv[1],$l);} #bool concat swap the false true values in string
if(in_array($s,["0101","1010","0000"])){die("stuck");} # NS WE NESW -> stuck = end program
$x=strpos($s,"1"); # find the first false value for an begin for the sort algorithm
$t=strstr($j=join($f),$f[$x]).strstr($j,$f[$x],1); # create the sort pattern
#sort algorithm example sort string = NESW-> N is not in the string
function c($x,$y){
    global $t;
    return strpos($t,$x)<=>strpos($t,$y); # e.g. comparison E<=>W =-1 , W<=>S=1, W<=>W =0
}
$a=str_split($i); # Input in an array
usort($a,"c"); #sort array
echo join($a);# output array as string

1
代替function c($x,$y){global$t,$p;return$p($t,$x)<=>$p($t,$y);}$a=str_split($i);usort($a,c);,您可以使用$a=str_split($i);usort($a,function($x,$y)use($t,$p){return$p($t,$x)<=>$p($t,$y);});并保存5个字节。太空飞船的操作员确实帮助了这种排序。为了让您了解我的工作,我将该函数移至usort(),使其成为匿名函数。然后,global我已经使用而不是(从不使用它)function(...)use($t,$p){...}。该use(...)语法允许您将变量传递到匿名函数主体中(它也接受续集)。
伊斯梅尔·米格尔

@IsmaelMiguel感谢您的精彩解释。
约尔格Hülsermann

别客气。我真的很喜欢use()匿名函数。您应该使用和滥用它。
伊斯梅尔·米格尔

1

批处理,216字节

@echo off
set/pt=
set/an=2,e=4,s=8,w=16,r=0
:l
set/ar^|=%t:~0,1%
set t=%t:~1%
if not "%t%"=="" goto l
set/a"o=449778192>>r&3,l=1053417876>>r&3"
if %l%==0 (echo stuck)else set t=NESWNE&call echo %%t:~%o%,%l%%%

我的JavaScript答案的简单移植。以大写或小写形式输入STDIN。


1

的JavaScript(ES6),108个 107 106 104字节

s=>(r=t=`NESWNE`,s.replace(/./g,c=>r|=2<<t.search(c)),t.substr(449778192>>r&3,1053417876>>r&3)||`stuck`)

累积一个方向接近汽车的位掩码,并提取优先级字符串的适当部分。


Uncaught SyntaxError: Invalid regular expression: missing /
Cyoce

@Cooce糟糕。发生的事情是浏览器在那时包装了代码,我以为换行符已经进入了。抱歉。
尼尔

没问题,只是让您知道。
Cyoce
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.