CJam,44 42 40字节
qN+ee_{Xa/~\+XW=eu__el=!\'@-*m<Xa+}fXWf=
输出包含尾随换行符。
在这里测试。
说明
我没有反复移动字母,而是重复删除字母,相应地旋转字符串,然后重新插入字母。这样做有一个陷阱:我们需要能够区分字符串的开头和字符串的结尾(在简单的旋转之后就无法区分)。这就是为什么我们在末尾插入一个换行符作为保护符(换行符之前的字母是字符串的末尾,字母后面的是开头)。奖金的是,这会自动返回最后一个字符串到正确的旋转在换行实际上是在字符串的结尾。
lN+ e# Read input and append a linefeed.
ee e# Enumerate the array, so input "bob" would become [[0 'b] [1 'o] [2 'b] [3 N]]
e# This is so that we can distinguish repeated occurrences of one letter.
_{ e# Duplicate. Then for each element X in the copy...
Xa/ e# Split the enumerated string around X.
~ e# Dump the two halves onto the stack.
\+ e# Concatenate them in reverse order. This is equivalent to rotating the current
e# character to the front and then removing it.
XW= e# Get the character from X.
eu e# Convert to upper case.
_ e# Duplicate.
_el=! e# Check that convert to lower case changes the character (to ensure we have a
e# letter).
\'@- e# Swap with the other upper-case copy and subtract '@, turning letters into 1 to
e# 26 (and everything else into junk).
* e# Multiply with whether it's a letter or not to turn said junk into 0 (that means
e# everything which is not a letter will be moved by 0 places).
m< e# Rotate the string to the left that many times.
Xa+ e# Append X to the rotated string.
}fX
Wf= e# Extract the character from each pair in the enumerated array.
要了解为什么它最终在正确的位置,请考虑hi*bye
示例的最后一次迭代。处理完之后e
,枚举字符串将位于以下位置:
[[4 'y] [6 N] [2 '*] [0 'h] [1 'i] [3 'b] [5 'e]]
首先,我们在换行符周围进行拆分,并以相反的顺序连接各部分:
[[2 '*] [0 'h] [1 'i] [3 'b] [5 'e] [4 'y]]
现在,换行符可以在此字符串的开头或结尾。但是,由于换行符只是标记字符串结尾的保护符,因此这意味着字符实际上按正确的顺序排列。现在,换行符不是字母,因此数组根本不会旋转。因此,当我们添加换行符时,它会移到它所属的位置,并且一切都按照我们要查找的顺序进行:
[[2 '*] [0 'h] [1 'i] [3 'b] [5 'e] [4 'y] [6 N]]
如果有人想比较较长的测试用例,则可以得到一些其他结果:
Hello, World!
,W oeHlo!lrld
Programming Puzzles & Code Golf
ago fgliPomomnrr elP& uC dezzsG
The quick brown fox jumps over the lazy dog
t eg chbi ko qfTounyzrj omw epx ueoahs rlvd
abcdefghijklmnopqrstuvwxyz
aqbrcdsetfguhivjwklxmnyozp
zyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyz
我喜欢最后一个。:)