CJam,25 − 25 = 0字节
q~1,*_@{[\{1$^}/_](;)\}/;
这是仅低于GolfScript答案的直CJam端口,因为看完之后马丁布特内尔的答案,我意识到,我可以一个字节保存由于CJam的处理整数和字符类型。(从根本上讲,CJam不需要1&用来将ASCII字符强制转换为GolfScript代码中的位,但确实需要一个前缀q来读取输入。)我通常认为这种琐碎的端口是一个便宜的把戏,但取得零分这对海事组织来说是值得的。
无论如何,该程序的工作方式与下面的原始GolfScript程序完全相同,因此请参考其说明和使用说明。像往常一样,您可以使用此在线解释器测试CJam版本。
GolfScript,26 − 25 = 1字节
~1,*.@{[1&\{1$^}/.](;)\}/;
该解决方案仅对输入字符串进行一次迭代,因此我相信它有资格获得−25字节的奖励。它通过内部维护一个k元素数组来工作,该数组存储k个预迭代中的每一个的当前位。
输入应通过stdin进行,格式为"1111111" 3,例如,带引号的字符串0和1字符,后跟数字k。输出将以不带引号的位串的形式输出到stdout。
在线测试此代码。(如果程序超时,请尝试重新运行它; Web GolfScript服务器因随机超时而臭名昭著。)
这是该程序的扩展版本,带有注释:
~ # eval the input, leaving a string and the number k on the stack
1,* # turn the number k into an array of k zeros ("the state array")
. # make a copy of the array; it will be left on the stack, making up the
# first k bits of the output (which are always zeros)
@ # move the input string to the top of the stack, to be iterated over
{
[ # place a start-of-array marker on the stack, for later use
1& # zero out all but the lowest bit of this input byte
\ # move the state array to the top of the stack, to be iterated over
{ 1$^ } / # iterate over each element of the state array, XORing each
# element with the previous value on the stack, and leave
# the results on the stack
. # duplicate the last value on the stack (which is the output bit we want)
] # collect all values put on the stack since the last [ into an array
(; # remove the first element of the array (the input bit)
) # pop the last element (the duplicated output bit) off the array
\ # move the popped bit below the new state array on the stack
}
/ # iterate the preceding code block over the bytes in the input string
; # discard the state array, leaving just the output bits on the stack
基本上,像大多数迭代解决方案一样,此代码可以理解为应用递归
b 我,Ĵ:= b 我,(Ĵ -1) ⊕ b (我 -1),(Ĵ -1) ,
其中b 0,Ĵ是Ĵ个输入比特(对Ĵ ≥1),b ķ,Ĵ是Ĵ个输出比特,和b 我,0 = 0通过假设。所不同的是,而迭代解决方案,实际上,“逐行”计算复发(即,第一b 1,Ĵ所有Ĵ,然后b 2,Ĵ等),该解决方案,而不是计算其“列由列”(或更准确地说,是“对角线对角线”),首先计算b i,i等于1≤i≤ ķ,然后b 我,我 1,然后b 我,我 2等
这种方法的一个(理论上的)优点是,原则上,此方法可以仅使用O(k)存储来处理任意长的输入字符串。当然,无论如何运行程序之前,GolfScript解释器都会自动将所有输入读入内存,这在很大程度上抵消了这一优势。