代码高尔夫 - 文字扰乱器

发布于 2024-08-04 19:09:38 字数 822 浏览 10 评论 0原文

请按照我下面给出的示例输入和输出,用尽可能短的源代码来回答将任意明文转换为其相应密文的程序。 CPU 时间最少或内存使用量最少的奖励积分*。

示例 1:

明文:敏捷的棕色狐狸跳过了懒狗。 Supercalifragilisticexpialidocious!

密文: eTh kiquc nobrw xfo smjup rvoe eth yalz .odg !uioiapeislgriarpSueclfaiitcxildcos

示例 2:

明文: 123 1234 12345 123456 1234567 12345678 123456789

C密文:312 4213 53124 642135 7531246 86421357 975312468

规则:

  1. 标点符号被定义为包含在最接近的单词中。
  2. 单词的中心被定义为ceiling((strlen(word)+1)/2)。
  3. 空白被忽略(或折叠)。
  4. 奇怪的单词首先向右移动。甚至单词也会先向左移动。

您可以将其视为向后读取所有其他字符(从单词末尾开始),然后向前读取其余字符。公司 => XoXpXrXtXoX =>尼亚奥·科普托。

感谢那些指出我的描述中不一致之处的人。这导致你们中的许多人走上了错误的道路,对此我深表歉意。规则#4 应该可以解决问题。

*仅当杰夫·阿特伍德决定这样做时才会授予奖励积分。因为我没有和他确认过,所以可能性很小。对不起。

Please answer with the shortest possible source code for a program that converts an arbitrary plaintext to its corresponding ciphertext, following the sample input and output I have given below. Bonus points* for the least CPU time or the least amount of memory used.

Example 1:

Plaintext: The quick brown fox jumps over the lazy dog. Supercalifragilisticexpialidocious!

Ciphertext: eTh kiquc nobrw xfo smjup rvoe eth yalz .odg !uioiapeislgriarpSueclfaiitcxildcos

Example 2:

Plaintext: 123 1234 12345 123456 1234567 12345678 123456789

Ciphertext: 312 4213 53124 642135 7531246 86421357 975312468

Rules:

  1. Punctuation is defined to be included with the word it is closest to.
  2. The center of a word is defined to be ceiling((strlen(word)+1)/2).
  3. Whitespace is ignored (or collapsed).
  4. Odd words move to the right first. Even words move to the left first.

You can think of it as reading every other character backwards (starting from the end of the word), followed by the remaining characters forwards. Corporation => XoXpXrXtXoX => niaorCoprto.

Thank you to those who pointed out the inconsistency in my description. This has lead many of you down the wrong path, which I apologize for. Rule #4 should clear things up.

*Bonus points will only be awarded if Jeff Atwood decides to do so. Since I haven't checked with him, the chances are slim. Sorry.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

莫言歌 2024-08-11 19:09:38

Python,50 个字符

对于 i 中的输入:

' '.join(x[::-2]+x[len(x)%2::2]for x in i.split())

处理自己 IO 的替代版本:

print ' '.join(x[::-2]+x[len(x)%2::2]for x in raw_input().split())

如果包含空格,则总共 66 个字符。 (从技术上讲,如果从命令行运行,则可以省略 print,因为代码的评估值默认显示为输出。)


使用 reduce 的替代版本:

' '.join(reduce(lambda x,y:y+x[::-1],x) for x in i.split())

59人物。

i 中输入的原始版本(偶数和奇数都先向右):

' '.join(x[::2][::-1]+x[1::2]for x in i.split())

48 个字符,包括空格。

另一个替代版本(虽然稍长)稍微更有效:

' '.join(x[len(x)%2-2::-2]+x[1::2]for x in i.split())

(53 个字符)

Python, 50 characters

For input in i:

' '.join(x[::-2]+x[len(x)%2::2]for x in i.split())

Alternate version that handles its own IO:

print ' '.join(x[::-2]+x[len(x)%2::2]for x in raw_input().split())

A total of 66 characters if including whitespace. (Technically, the print could be omitted if running from a command line, since the evaluated value of the code is displayed as output by default.)


Alternate version using reduce:

' '.join(reduce(lambda x,y:y+x[::-1],x) for x in i.split())

59 characters.

Original version (both even and odd go right first) for an input in i:

' '.join(x[::2][::-1]+x[1::2]for x in i.split())

48 characters including whitespace.

Another alternate version which (while slightly longer) is slightly more efficient:

' '.join(x[len(x)%2-2::-2]+x[1::2]for x in i.split())

(53 characters)

夏夜暖风 2024-08-11 19:09:38

J,58 个字符

>,&.>/({~(,~(>:@+:@i.@-@<.,+:@i.@>.)@-:)@<:@#)&.><;.2,&' '

J, 58 characters

>,&.>/({~(,~(>:@+:@i.@-@<.,+:@i.@>.)@-:)@<:@#)&.><;.2,&' '
标点 2024-08-11 19:09:38

Haskell,64 个字符

unwords.map(map snd.sort.zip(zipWith(*)[0..]$cycle[-1,1])).words

好吧,如果您添加必要的“导入列表”。

Haskell, 64 characters

unwords.map(map snd.sort.zip(zipWith(*)[0..]$cycle[-1,1])).words

Well, okay, 76 if you add in the requisite "import List".

ˉ厌 2024-08-11 19:09:38

Python - 69 个字符

(包括空格和换行符)

这处理所有 I/O。

for w in raw_input().split():
 o=""
 for c in w:o=c+o[::-1]
 print o,

Python - 69 chars

(including whitespace and linebreaks)

This handles all I/O.

for w in raw_input().split():
 o=""
 for c in w:o=c+o[::-1]
 print o,

Perl,78 个字符

用于在 $_ 中输入。如果不可接受,请在开头添加 $_=<>;$_=$s; 六个字符。换行符只是为了可读性。

for(split){$i=length;print substr$_,$i--,1,''while$i-->0;
print"$_ ";}print $/

Perl, 78 characters

For input in $_. If that's not acceptable, add six characters for either $_=<>; or $_=$s; at the beginning. The newline is for readability only.

for(split){$i=length;print substr$_,$i--,1,''while$i-->0;
print"$_ ";}print $/
霓裳挽歌倾城醉 2024-08-11 19:09:38

C,140 个字符

格式良好:

main(c, v)
  char **v;
{
  for( ; *++v; )
  {
    char *e = *v + strlen(*v), *x;
    for(x = e-1; x >= *v; x -= 2)
      putchar(*x);
    for(x = *v + (x < *v-1); x < e; x += 2)
      putchar(*x);
    putchar(' ');
  }
}

压缩:

main(c,v)char**v;{for(;*++v;){char*e=*v+strlen(*v),*x;for(x=e-1;x>=*v;x-=2)putchar(*x);for(x=*v+(x<*v-1);x<e;x+=2)putchar(*x);putchar(32);}}

C, 140 characters

Nicely formatted:

main(c, v)
  char **v;
{
  for( ; *++v; )
  {
    char *e = *v + strlen(*v), *x;
    for(x = e-1; x >= *v; x -= 2)
      putchar(*x);
    for(x = *v + (x < *v-1); x < e; x += 2)
      putchar(*x);
    putchar(' ');
  }
}

Compressed:

main(c,v)char**v;{for(;*++v;){char*e=*v+strlen(*v),*x;for(x=e-1;x>=*v;x-=2)putchar(*x);for(x=*v+(x<*v-1);x<e;x+=2)putchar(*x);putchar(32);}}
只是一片海 2024-08-11 19:09:38

Lua

130 个字符函数,147 个字符函数程序

Lua 在代码高尔夫中没有得到足够的喜爱——也许是因为当你有像 function/end< 这样的长关键字时很难编写一个短程序。 /code>、if/then/end 等。

首先,我详细地编写了该函数并附有解释,然后将其重写为一个压缩的独立函数,然后我在命令行指定的单个参数上调用该函数。

我必须使用

标签来格式化代码,因为 Markdown 在格式化 Lua 方面做得很糟糕。

从技术上讲,您可以通过内联函数来获得更小的运行程序,但这种方式更加模块化:)

t = "The quick brown fox jumps over the lazy dog. Supercalifragilisticexpialidocious!"
T = t:gsub("%S+", -- for each word in t...
                  function(w) -- argument: current word in t
                    W = "" -- initialize new Word
                    for i = 1,#w do -- iterate over each character in word
                        c = w:sub(i,i) -- extract current character
                        -- determine whether letter goes on right or left end
                        W = (#w % 2 ~= i % 2) and W .. c or c .. W
                    end
                    return W -- swap word in t with inverted Word
                  end)


-- code-golf unit test
assert(T == "eTh kiquc nobrw xfo smjup rvoe eth yalz .odg !uioiapeislgriarpSueclfaiitcxildcos")

-- need to assign to a variable and return it,
-- because gsub returns a pair and we only want the first element
f=function(s)c=s:gsub("%S+",function(w)W=""for i=1,#w do c=w:sub(i,i)W=(#w%2~=i%2)and W ..c or c ..W end return W end)return c end
--       1         2         3         4         5         6         7         8         9        10        11        12        13
--34567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
-- 130 chars, compressed and written as a proper function

print(f(arg[1]))
--34567890123456
-- 16 (+1 whitespace needed) chars to make it a functioning Lua program, 
-- operating on command line argument

输出:

$ lua insideout.lua 'The quick brown fox jumps over the lazy dog. Supercalifragilisticexpialidocious!'
eTh kiquc nobrw xfo smjup rvoe eth yalz .odg !uioiapeislgriarpSueclfaiitcxildcos

我对 Lua 还很陌生,所以我希望看到一个更短的解决方案(如果有)。


For a minimal cipher on all args to stdin, we can do 111 chars:

for _,w in ipairs(arg)do W=""for i=1,#w do c=w:sub(i,i)W=(#w%2~=i%2)and W ..c or c ..W end io.write(W ..' ')end

但这种方法确实会像其他一些解决方案一样输出尾随空格。

Lua

130 char function, 147 char functioning program

Lua doesn't get enough love in code golf -- maybe because it's hard to write a short program when you have long keywords like function/end, if/then/end, etc.

First I write the function in a verbose manner with explanations, then I rewrite it as a compressed, standalone function, then I call that function on the single argument specified at the command line.

I had to format the code with <pre></pre> tags because Markdown does a horrible job of formatting Lua.

Technically you could get a smaller running program by inlining the function, but it's more modular this way :)

t = "The quick brown fox jumps over the lazy dog. Supercalifragilisticexpialidocious!"
T = t:gsub("%S+", -- for each word in t...
                  function(w) -- argument: current word in t
                    W = "" -- initialize new Word
                    for i = 1,#w do -- iterate over each character in word
                        c = w:sub(i,i) -- extract current character
                        -- determine whether letter goes on right or left end
                        W = (#w % 2 ~= i % 2) and W .. c or c .. W
                    end
                    return W -- swap word in t with inverted Word
                  end)


-- code-golf unit test
assert(T == "eTh kiquc nobrw xfo smjup rvoe eth yalz .odg !uioiapeislgriarpSueclfaiitcxildcos")

-- need to assign to a variable and return it,
-- because gsub returns a pair and we only want the first element
f=function(s)c=s:gsub("%S+",function(w)W=""for i=1,#w do c=w:sub(i,i)W=(#w%2~=i%2)and W ..c or c ..W end return W end)return c end
--       1         2         3         4         5         6         7         8         9        10        11        12        13
--34567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
-- 130 chars, compressed and written as a proper function

print(f(arg[1]))
--34567890123456
-- 16 (+1 whitespace needed) chars to make it a functioning Lua program, 
-- operating on command line argument

Output:

$ lua insideout.lua 'The quick brown fox jumps over the lazy dog. Supercalifragilisticexpialidocious!'
eTh kiquc nobrw xfo smjup rvoe eth yalz .odg !uioiapeislgriarpSueclfaiitcxildcos

I'm still pretty new at Lua so I'd like to see a shorter solution if there is one.


For a minimal cipher on all args to stdin, we can do 111 chars:

for _,w in ipairs(arg)do W=""for i=1,#w do c=w:sub(i,i)W=(#w%2~=i%2)and W ..c or c ..W end io.write(W ..' ')end

But this approach does output a trailing space like some of the other solutions.

老娘不死你永远是小三 2024-08-11 19:09:38

对于 s 中的输入:

f=lambda t,r="":t and f(t[1:],len(t)&1and t[0]+r or r+t[0])or r
" ".join(map(f,s.split()))

Python,90 个字符,包括空格。

For an input in s:

f=lambda t,r="":t and f(t[1:],len(t)&1and t[0]+r or r+t[0])or r
" ".join(map(f,s.split()))

Python, 90 characters including whitespace.

泪之魂 2024-08-11 19:09:38

TCL

125个字符

set s set f foreach l {}
$f w [gets stdin] {$s r {}
$f c [split $w {}] {$s r $c[string reverse $r]}
$s l "$l $r"}
puts $l

TCL

125 characters

set s set f foreach l {}
$f w [gets stdin] {$s r {}
$f c [split $w {}] {$s r $c[string reverse $r]}
$s l "$l $r"}
puts $l
岁月流歌 2024-08-11 19:09:38

Bash - 133,假设输入在 $w 变量中,

很好

for x in $w; do 
    z="";
    for l in `echo $x|sed 's/\(.\)/ \1/g'`; do
        if ((${#z}%2)); then
            z=$z$l;
        else
            z=$l$z;
        fi;
    done;
    echo -n "$z ";
done;
echo

压缩得

for x in $w;do z="";for l in `echo $x|sed 's/\(.\)/ \1/g'`;do if ((${#z}%2));then z=$z$l;else z=$l$z;fi;done;echo -n "$z ";done;echo

,所以它输出一个尾随空格。

Bash - 133, assuming input is in $w variable

Pretty

for x in $w; do 
    z="";
    for l in `echo $x|sed 's/\(.\)/ \1/g'`; do
        if ((${#z}%2)); then
            z=$z$l;
        else
            z=$l$z;
        fi;
    done;
    echo -n "$z ";
done;
echo

Compressed

for x in $w;do z="";for l in `echo $x|sed 's/\(.\)/ \1/g'`;do if ((${#z}%2));then z=$z$l;else z=$l$z;fi;done;echo -n "$z ";done;echo

Ok, so it outputs a trailing space.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文