views:

526

answers:

10

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.

+7  A: 

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)

Amber
What language is that?
recursive
It's in Python.
Amber
Please post the language and character count, following in the tradition of code-golf. ;)
Will Bickford
I still had to tweak it a little, had a typo or two. Will post the character count when I double check. :)
Amber
That only seems to work for odd length input words.
Greg Hewgill
Um, this doesn't work.
recursive
Will look into making it work then. :)
Amber
There we go. Updated version that appears to work correctly for the entirety of the test string, in 69 characters (inc. whitespace).
Amber
len(x)%2and-1or-2 is the same as len(x)%2-2
recursive
Yeah, I was thinking about that as I was working on other stuff. Modified.
Amber
I went for strokes, but i think this loses all hope of getting bonus points for efficiency.
Jimmy
I'm going to add back in the slightly-more-strokes version as an alternate since efficiency can be nice too.
Amber
P Daddy
It got fixed to work for even-size words a while ago. :)
Amber
Your version gives 3124 where it should give 4213 for an input of 1234.
Will Bickford
Because you changed/clarified the definition. Please try to be more complete next time, or accept answers that match the original description.
Amber
Annnnnd another, in 50 characters instead.
Amber
A: 

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.

Greg Hewgill
Are you not counting whitespace?
recursive
I'm not. Should I?
Greg Hewgill
It's common practice in golf to count it. BTW, you can eliminate some of those spaces. Like every space that doesn't separate two letters.
recursive
Thanks, updated.
Greg Hewgill
recursive
I just noticed that extra space before `or`, but removing the space after `1` failed (perhaps because `e` is valid in a floating point number).
Greg Hewgill
...but I can remove it before `and`. :)
Greg Hewgill
+1  A: 

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 $/
hobbs
I would just add 10 characters for `perl -ne''` - it's not that much more, and we could shave a few off by using 5.10 (change `print $/` to `say""` or at least remove the space between `print` and the variable, perhaps rewrite to condense two `--` into `-=2` and see if you can't shrink it a character, remove the `;` before the ending bracket of the loop).
Chris Lutz
Also, changing the `while()` loop to a C-style `for()` loop might (might) shave a few characters. Haven't tried it.
Chris Lutz
I didn't put maximum effort into this one; I've been working on some real-world code for a change. I'm not sure whether the `--` can be eliminated, but and given the discussion above I'm not even sure whether I'm on spec. If you want this entry, go ahead and edit and you can have it :)
hobbs
s/but and/and/ ;)
hobbs
+3  A: 

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,
recursive
+4  A: 

J, 58 characters

>,&.>/({~(,~(>:@+:@i.@-@<.,+:@i.@>.)@-:)@<:@#)&.><;.2,&' '
ephemient
Reading all these Code Golfs, I have come to hate J. Knowing that there is this language that can do so much, with so little. And what I hate is that I have no idea what this means. It looks like a bunch of mutated smilies to me :P
Mike Cooper
I think every SO golfer needs to download a J interpreter and verify these J answers. There are so many, and I know some of them are just people writing smileys.
Chris Lutz
Obviously, it's not actually a program for the question but instead a secretly coded message to other J programmers that laughs at all the people who don't know J. Obviously.
Amber
I actually haven't seen any dishonest J answers yet. (Chris may be more active on SO than I.) It's true, though, that there's not many people who double-check these...
ephemient
This is the first time i've seen J beaten by anything else in a code golf...
RCIX
Heh. Python's list comprehensions and slice notation happen to come in handy this time.
Amber
I can't say I'm skilled at J, but I agree: Python's slice notation is very useful here. The `(>:@+:@i.@-@<.,+:@i.@>.)@-:` bit in the middle tries to emulate it, but it's rather unexpectedly verbose in J.
ephemient
+4  A: 

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".

ephemient
+1  A: 

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.

Mark Rushakoff
Odd, i find lua is decnetly formatted on here...
RCIX
A: 

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.

Shin
+1  A: 

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);}}
Adam Rosenfield
Chris Lutz
Tried it -- it doesn't compile unless you also add `int c`, which is a couple more characters overall. Apparently you can't use mixed-style prototypes, which is quite sensible.
Adam Rosenfield
What are you compiling it with? I thought GCC would let it compile with all the warnings off, because they should be implicitly typed to int...
Chris Lutz
I've tried it with gcc-4.3.3, gcc-4.0.1, and gcc-3.4.6, all of which didn't like `main(c,char**v)`.
Adam Rosenfield
@Adam: You can shave off another 2 characters by changing `x=x==s-1?s:s+1` to `x=s+(x!=s-1)`. gcc 4.3.3 does not give a warning for that, even with `-Wall`.
Mark Rushakoff
@Mark: Thanks, I've incorporated that into the answer.
Adam Rosenfield
A: 

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
TokenMacGuy