Two-way Palindromic Closure Generator
Pyth, 22 19
hfq_TTsm,+z_d+_dzyz
Try it online.
Explanation
The two-way palindromic closure is either of the form AX
or XA
, where X
is the input string and A
is a substring of X
. I actually has to be a contiguous substring of X
, a prefix for the one form, a suffix for the other form. But I don't care about these defails. A substring (contiguous or not) is all I need in Pyth.
Implicit: z = raw_input() // Read a string
yz A list with all substrings (contiguous or not) of z
m For each of these substrings d, build
, a pair of two strings:
+z_d ( z + inveres(d) ,
+_dz inverse(d) + z )
s Sum (put all created pairs into a list)
fq_TT filter elements T, where inverse(T) == T (Palindrom)
h Take the first element
Edit
The old version ordered the the strings after filtering by length .olN...
. Just realized, that y
returns the substrings ordered by length. So these palindromes are already sorted.
Clip, 40
(sl`f[a=ava}+m[i+v+ixx}Rlxm[i+xvu0ix}Rlx
Example
Documents>java -jar Clip4.jar palindrome.clip
abcb
abcba
Explanation
(sl` .- The shortest -.
f[a=ava} .- palindrome -.
+ .- among the following two sets: -.
m[i }Rlx .- For each number up to length(x) -.
+ .- combine -.
v+ix .- the last i chars of x, reversed -.
x .- and x. -.
m[i }Rlx .- For each number up to length(x) -.
+ .- combine -.
x .- x and -.
vu0ix .- the first i chars of x, reversed.-.
CJam, 30 bytes
Was really hoping to see a CJam answer by now.. So here it goes :P
q:Q,{)QW%/(Q+Q@+s}%{,}${_W%=}=
I really hate that {,}$
block in there, but I get an unordered list of possible palindromes due to the generation algorithm I am using.
Code explanation
q:Q,{ }% "Read the input string, store in Q, take length and";
"run the code block that many times";
)QW% "Increment the iteration index and Put reversed Q on stack";
/ "Split reversed Q into parts of incremented iteration index";
(Q+ "Take out the first part and prepend it to Q";
Q@+s "Take the rest of the parts and append them to Q";
{,}$ "At this point, we have all possible prepended and appended";
"sequences of the input string. Sort them by length";
{_W%=}= "Take the first sequence which is a palindrome";
Try it online here