Rosencrantz和Guildenstern是代码


10

在荒诞戏中,罗森克兰兹和吉尔登斯滕死了,两个主要角色罗森克兰兹吉尔登斯特恩(还是他们??)总是混为一谈,是因为谁感觉到自己缺乏身体,或者有时是自己的身体部位是什么?个人身份。如果他们甚至改头换面都不会荒谬吗?

您的任务是编写一个函数,该函数接受长度大于7个字符的偶数长度(并且设计为4的倍数)的字符串,将其拆分并随机播放。

分割如下:字符串应为format "abscd",其中s为分隔符。第一部分和分隔符abs将是字符串的前半部分,而后半部分将是cd

长度 a将是(string length / 4) - 1

长度 b将是(string length / 4)

长度 s将是1

长度 c将是(string length / 4) + 1

长度 d将是(string length / 4) - 1

这可能确实令人困惑,所以让我向您展示一些示例

("a" + "bb" + "s" + "ccc" + "d").length //8
  1     2      1      3      1
|-------4--------|  |----4-----| <--- (4 is half of 8)

("rosen" + "crantz" + "&" + "guilden" + "stern").length  //24
    5         6        1        7          5

("foo" + "barr" + "?" + "barry" + "foo").length
   3       4       1      5         3

最后:

然后,您将周围的部分随机播放,输出 adscb

例如 "rosencrantz&guildenstern" --> "rosenstern&guildencrantz"

"foobarr?barryfoo" --> "foofoo?barrybarr"

Rulez:

  1. 标准漏洞禁止
  2. 可接受的答案:通过一个输入字符串获取输入并返回一个输出字符串的函数
  3. 如果输入字符串与上面提供的要求不匹配,则您的代码必须错误输出(无论是哪种类型ExceptionError
  4. 这是code-golf,因此(每种语言中)最短的(有效)答案会获胜!
  5. 一线客的奖励积分:-)(不是真的,只是很酷的积分)

6
关于您的黑帮统治者:通常不建议使用“功能”,因为通常很难对其进行定义。此外,还通常避免处理无效输入,因为它通常归结为令人讨厌的样板代码。
乔纳森·弗雷希

@JonathanFrech我认为输入验证的挑战是一个有趣的问题,因为可以通过数组遍历,分支逻辑,RegEx测试等多种方式来处理输入验证,因此对这些方法的优化可能会带来额外的挑战_(ツ)_ /¯我将尝试另一场高尔夫挑战赛的挑战:-)
迈克尔·迈克尔(Michael)

2
后来,每个人都在尝试获得更灵活的io方法,以在他们喜欢的高尔夫语言中编写代码。和tfw几乎在所有问题上都会发生
风车饼干


1
@NathanMerrill在规范中提到输入的长度必须大于7个字符,并且其长度必须可被4整除,Jo King建议输入长度为4的测试用例,例如“ abcd”,这应该会出错
Thaufeki

Answers:


11

K(oK)35 34 33字节

{$[8>#x;.;<x!4!-&4#-1 0 2+-4!#x]}

在线尝试!

没有输入验证(用于ngn的赏金),25 24 23字节

{<x!4!-&4#-1 0 2+-4!#x}

在线尝试!

很快了解了一些K,然后查看动词列表,我认为可以在这里使用另一种方法(使用cut)。而且效果很好。

怎么运行的

{<x!4!-&4#-1 0 2+-4!#x}
                 -4!#x    Length divided by four (floor division)
        4#-1 0 2+         Generate lengths (x/4-1, x/4, x/4+2, x/4-1)
       &                  Generate that many 0, 1, 2, 3's
    4!-                   Negate and modulo 4; effectively swap 1 and 3
 <x!                      Sort the original string by above

{$[8>#x;.; <code> ]}  Input validation
 $[8>#x           ]   If the length is less than 8
        .             Dynamically generate an error
           <code>     Otherwise, run the main code

@ngn我的眼睛怎么了Oo
Bubbler

3

Perl 6的60 58个字节

-2个字节,感谢Jo King

{[~] .rotor($_/4 X-1,0,+^-$_+>2,-1,1)[0,4,2,3,1;*]}o*.comb

在线尝试!

发生错误时,抛出“旋转子列表长度超出范围”。

说明

{               # Anonymous block
 [~]            # Join
   .rotor(      # Split into sublists of specific length
     $_/4 X-    # Subtract from len/4
     1,
     0,
     +^-$_+>2,  # (len-1)>>2
                #   subtraction yields 1 if len is multiple of 4
                #   otherwise a value less than 1 causing an error
     -1,       
     1)
   [0,4,2,3,1;*]  # Rearrange sublists and take inner elements
}o*.comb          # Split into characters and feed into block

3

J36 35字节

5;@A.](<;.2~;)1<@{."+~1 0 _2 1-4%~#

在线尝试!

-1字节乘以{.+负长度&;.2切成“结束”标记。

原始答案,36个字节

5;@A.](<;.1~;)1<@{."+~_1 0 2 _1+4%~#

在线尝试!

ngn在对较早的K答案的评论中提到“剪切”,这让我尝试了具有相同“ cut”的J(我不知道K是如何工作的)。

怎么运行的

5;@A.](<;.1~;)1<@{."+~_1 0 2 _1+4%~#  Monadic train.
                                4%~#  Length divided by four
                      _1 0 2 _1+      Generate the four segment lengths
              1<@{."+~  Generate [1 0 0...] boxed arrays of those lengths
      (     ;)          Raze; unbox and concatenate
     ] <;.1~            Cut the input string on ones as starting marker, then box each
5  A.  Rearrange the boxes in the order 0 3 2 1
 ;@    Raze again

请注意,此函数自动处理无效输入:

  • 如果输入长度不是四的倍数,则{.抛出domain error因为其length参数必须为整数。
  • 如果输入长度为4,则剪切仅产生两个片段,并5 A.抛出index error
  • 如果输入长度为0,则cut的两个参数的长度不同,因此length error将引发该错误。

3

Python 3中103 102 101 97 88个 86个 84字节

def f(s):l=len(s);l//=4*(l%4<1<l/4);return s[:l-1]+s[1-l:]+s[2*l-1:1-l]+s[l-1:2*l-1]

在线尝试!

并不是真正的一线客,但 ;每行比换行和缩进少一个字节。

ZeroDivisionError如果输入字符串的长度小于8或不是4的整数倍,则抛出该异常。

也适用于Python 2。

-4个字节,感谢Jo King

-9字节归功于ovs

-2个字节,感谢Jonathan Frech

-2个字节归功于Bubbler


@JoKing感谢您的提示,不胜感激:)
Axim


@ovs很好地抓住了相邻的索引,至于括号,我尝试了至少20分钟,看看是否可以摆脱其中的一些索引,然后我完全想不到了,//=因为最外面的对的更改变得多余了。谢谢一群!
Axim

2
-l+1<-> 1-l
乔纳森·弗雷希

1
将两个不等式合并为84个字节
Bubbler

2

Perl 6,78个字节

*.comb[0..*/4-2,3* */4+1..*,*/2-1/(*>7)..3* */4,*/4-1/(*%%4)..*/2-2].flat.join

在线尝试!

匿名代码块,它接收字符串并返回修改后的字符串(如果有效),否则返回零除错误。我知道我可以直接修改数组,因此可以交换字符串的两个部分,但是我不太清楚。


2

K(NGN / K) 120个 113 103 99 95字节

{$[(r>7)&0=4!r:#:x;{g:(s:*|(y*2)#x)\x;((y-1)#*g),((-y-1)#*|g),s,((y+1)#*|g),(-y)#*g}[x;r%4];l]}

希望可以进一步研究,包括一个额外的功能,用于测试字符串长度是否可以被四整除,如果输入无效,则针对未声明的变量输出错误

编辑:长度大于7的缺少条件,包括

编辑:合并为一个函数,删除了冗余变量声明

在线尝试!


1
这可能要短得多。您知道“ cut”(indices_string)吗?ping通我在果园里,如果我要解释一下
NGN

1
我可以用34个字节来做:)
ngn

我知道剪切,但是我没有考虑使用它... 34个字节?当我回到家时,我将
不得不再试一遍

我应该提到:我的解决方案不能确保无效输入(长度<= 7)会导致错误
ngn

1

视网膜0.8.2、58或73或83或93字节

((((.)))*?)(.(?<-2>.)+)(...(?<-3>.)+)((?<-4>.)+)$
$1$7$6$5

在线尝试!说明:

((((.)))*?)

捕获 a进去$1,并使其尽可能短*?$#2$#3$#4以的长度结束a

(.(?<-2>.)+)

b在中捕获$4。将(?<-2>.)+捕获到的长度a,而其他.的要求加1其长度。

(...(?<-3>.)+)

捕获 sc进入$6。它们的总长度是的长度的三倍a

((?<-4>.)+)

d在中捕获$7。它的长度不超过的长度a

$

我们做了a尽可能短的输入,但是我们仍然想达到输入的结尾。

$1$7$6$5

交流b与交流d

以上阶段未验证其输入。由于Retina没有运行时错误,因此有许多用于输入验证的选项:

G`^(....){2,}$

如果长度小于8或不是4的倍数,则不输出任何内容。(+ 15字节)

^(?!(....){2,}$).*
Error

产出 Error如果长度小于8或不是4的倍数,则。(+ 25字节)

+`^(....)*..?.?$|^(....)?$
.....$1

如果长度小于8或不是4的倍数,则挂起。(+ 35字节)


这不会在无效输入上引发错误(就那样令人讨厌)
Jo King

1

C(GCC)-Dx=memcpy-DL=(l-1)154个 158 160字节

如果输入字符串的长度不能被4或小于8个字符整除,则返回NULL。

感谢Rogem和Jonathan Frech的建议。

编辑:将预处理器定义移动到命令行,并动态分配字符串以严格符合难题。

f(s,t,l)char*s,*t;{l=strlen(s);l%4|l<8?t=0:(t=malloc(l+1),l/=4,x(t,s,L),x(t+L,s+3*l+1,L),x(t+2*L,s+L+l,l+2),x(t+3*l,s+L,l),t[4*l]=0);l=t;}//-Dx=memcpy -DL=(l-1)

在线尝试!


为什么t[80]呢 输入长度似乎没有上限。
乔纳森·弗雷希

@JonathanFrech我这样做是为了保存字节,但是您是正确的。我已更改了解决方案以malloc()代替使用。
ErikF

通过修改返回,返回值NULL用于无效输出,使用from的返回值memcpy(),类似于函数的宏来跳过类型,而C99可变长度数组则要跳过malloc()

为什么是160个字节,您算的是//还是-w
l4m2

@ l4m2 -w只是抑制警告的一种方便方式(因此更容易发现错误)。我通常在a后面添加命令行参数,//以使TIO为我计算字节数,然后从总数中减去1以说明执行此操作所需的一个额外字符。

1

果冻,28 个字节

L7»4ḍİ×L:4;;ĖÄƲFÄœṖ⁸⁽%[D¤ị$F

(如果允许使用完整的程序,我们可以删除尾随的内容。F
如果长度小于8或不能被4整除,ValueError则在将inf(浮点数)除以4-时,会产生整数-除法运算会产生NaN(也是浮点数)被铸成int

在线尝试!

怎么样?

L7»4ḍİ×L:4;;ĖÄƲFÄœṖ⁸⁽%[D¤ị$F - Link: list of characters
L                            - length
 7                           - literal seven
  »                          - maximum (of length & 7)
   4ḍ                        - divisible by four? (yields 1 for good inputs; 0 otherwise)
     İ                       - inverse (1 yields 1; 0 yields inf)
      ×L                     - multiply by length (length or inf)
        :4                   - integer divide by 4 (errors given inf)
              Ʋ              - last four links as a monad (f(x)):
          ;                  -   concatenate -> [x,x]
            Ė                -   enumerate -> [1,x]
           ;                 -   concatenate -> [x,x,[1,x]]
             Ä               -   cumulative sum (vectorises at depth 1) -> [x,x,[1,1+x]]
               F             - flatten -> [x,x,1,1+x]
                Ä            - cumulative sum -> [x,2x,2x+1,3x+2]
                   ⁸         - chain's left argument (the input)
                 œṖ          - partition at indices (chops up as per requirements)
                          $  - last two links as a monad (f(z)):
                        ¤    -   nilad followed by link(s) as a nilad:
                    ⁽%[      -     10342
                       D     -     decimal digits -> [1,0,3,4,2]
                         ị   -   index into z (rearranges the pieces as per requirements)
                           F - flatten (back to a list of characters)



1

JavaScript(ES6),97 89字节

@ l4m2节省了8个字节

s=>(l=s.length/4)<2||l%1?Z:s.replace(eval(`/(.{${l}})(.{${l+2}})(.{${l-1}})$/`),'$3$2$1')

在线尝试!


1
89B
l4m2


0

Java 8,135字节

s->{int l=s.length();l=l>7&l%4<1?l/4:l/0;return s.substring(0,l-1)+s.substring(3*l+1)+s.substring(2*l-1,3*l+1)+s.substring(l-1,2*l-1);}

ArithmeticException如果输入字符串不符合要求,则抛出(除以零)。在这里在线尝试

取消高尔夫:

s -> { // lambda function taking a String argument and returning a String
    int l = s.length(); // take the length of the input ...
    l = l > 7 &         // ... if it's  greater than 7 and ...
        l % 4 < 1       // ... a multiple of 4 ...
      ? l / 4           // ... divide by 4; otherwise ...
      : l / 0;          // ... error out (division by zero throws ArithmeticException)
    return // concatenate and return:
           s.substring(0, l - 1)             // a
         + s.substring(3 * l + 1)            // d
         + s.substring(2 * l - 1, 3 * l + 1) // sc
         + s.substring(l - 1, 2 * l - 1);    // b
}

建议l/=l>7&l%4<1?4:0;而不是l=l>7&l%4<1?l/4:l/0;
ceilingcat '19

0

C(gcc),129字节

通过修改返回。编译:

-Df(s)=({char t[l=strlen(s)];l%4|l<8?0:(l/=4,x(t,s+l*2-1,l-~l),x(x(x(s+l*3,s+l-1,l)-l-2,t,l+2)-l+1,t+l+2,l-1),s);}) -Dx=memcpy

源文件:

l;

在线尝试!

德戈尔夫

-Df(s)=({ // Function-like macro f. Takes a char* as a parameter.
          // Return value is a pointer to s if successful, and to NULL if string was invalid.
     char t[l=strlen(s)]; // Allocate a local temp string.
     l%4|l<8?0: // Detect invalid strings. Return 0 (NULL) on invalid string.
         (l/=4, // We're only really concerned with floor(len/4), and this will yield that.
             memcpy(t,s+l*2-1,l-~l), // Copy the second half of chars to the temp storage.
             memcpy( // Because memcpy returns the address of the destination, we can chain
                     // the calls to save quite a few bytes, even after x->memcpy substitution.
                 memcpy(memcpy(s+l*3,s+l-1,l) // Next, copy the second quarter to the end.
                     -l-2,t,l+2) // After that, we copy back the third quarter to its place.
                          -l+1,t+l+2,l-1) // Finally, copy the fourth quarter to where the second
                                          // quarter was.
                      ,s);}) // And return the pointer.
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.