Lua
130 char function, 147 char functioning program
Lua does not have enough love for code golf - perhaps because it is difficult to write a short program when you have long keywords, such as function / end , if / then / end , etc.
First, I write the function in a detailed way with explanations, then I rewrite it as a compressed, stand-alone function, then I call this function with the only argument specified on the command line.
I had to format the code with <pre></pre> tags because Markdown does a terrible job of formatting Lua.
Technically, you can get a smaller working program by inserting a function into it, but it is more modular :)
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 to Lua, so I would like to see a shorter solution, if any.
For minimal encryption for all stdin arguments, we can do 111 characters:
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 brings out a finite space similar to some other solutions.