半反转二进制字符串


12

这是我的Puzzling.SE问题的后续问题:我问是否有一个函数f将布尔字符串映射到布尔字符串,以便所有输入字符串b的f(f(b))= reverse(b)。(通过reverse,我的意思是反转位顺序的函数。)

上面的链接包含一个很好的肯定答案,并有一个很好的f''证明,但是您可能想在看之前自己考虑一下问题。

用尽可能少的字节实现这种功能f

  • 您可以从STDIN读取输入,也可以采用函数参数。并将结果字符串写入STDOUT或将其返回。

  • 无论哪种方式,您都可以使用两个不同字节的实际字符串或您选择的字符(例如01,或\x00\x01),或使用true和falsy值的数组/列表。选择两个值并坚持使用。

  • 单个应用f 的结果必须是二进制字符串本身:没有像b -> if b starts with 'x' then reverse(b[1:]) else 'x' + b... 这样的愚蠢答案。

  • 你的功能应该是合计的 ; 特别是,输入可以是空字符串,也可以是一比特长,等等。字符串的长度没有上限。

  • 它也应该是纯净的:在函数调用之间不要保留任何全局状态。输入字符串必须完全确定输出字符串。


输出的长度可以与输入的长度不同吗?
Luis Mendo

当然!(实际上,否则,证明挑战是不可能的。)
林恩

它必须对长度为1或零的字符串起作用吗?
CalculatorFeline

是; 功能必须是合计的。我已经在问题中澄清了!
林恩

Answers:



7

Python 2,64 69字节

def f(s):p=(s+s).find(s,1);return[s[~p::-1],s+s[:p]][len(s)/p%2]

取消高尔夫:

def f(s):
    p = (s+s).find(s,1)
    n = len(s)/p
    return s[:p][::1|n%-2] * -~(n-1^1)

这找到了字符串的周期,即最小的长度p,这s是一个长度p重复的字符串n(我在SO上找到了一种高尔夫球方法)。然后,如果n为奇数,则该周期再增加一个重复。如果n是偶数,它将删除一个重复周期并将其反转。

感谢@ Sp3000帮助实现了1 <-> 2、3 <-> 4等之间的功能映射。


...何时将更新未发布的代码?
CalculatorFeline

@CatsAreFluffy我没有计划修改非高尔夫代码,因为它使用相同的想法,只是有一些细微的差别。另一方面,英语是最新的。
feersum'3

2

Perl,49个 47字节

包括+2 -lp

基于@feersum的非常好的算法

使用STDIN上的输入运行,例如

perl -lp halfreverse.pl <<< "101001"

halfreverse.pl

/^(.+?)((\1\1?)*)$/;$_=$3eq$1?reverse$2:$_.$1

说明

/^               $/         Match the complete input string
  (.+?)                     Non-greedy match. Try only one digit at the start,
                            if that doesn't work try 2, then 3 etc. The string
                            being tried is remembered in backreference \1
       ((\1\1?)*)           Try to repeat \1 as many times as possible but
                            prefer in groups of 2. Fall back to only 1 at the
                            end of the string if the trailing part has an odd
                            number of \1 (so the total count is even)

   $3eq$1                   So the last match $3 equals the first match $1
         ?                  if and only if the total count is even
          reverse$2         If total count is even drop the first instance of
                   :        \1 and reverse
                    $_.$1   If total count is odd extend $_ by one instance
$_=                         Assign result

它是如何工作的??
CalculatorFeline
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.