Palindromic palindrome generator

Create a program, that converts input string to a palindrome starting with the input string. The program itself must be a palindrome.

For example input: neverod, print neveroddoreven. You should handle multi-word, multi-line inputs as well.

• This seems very similar to this question, except here we're generating instead of checking. Chances are the same tricks will be employed to make the program a palindrome, though. – Sp3000 Mar 16 '15 at 9:02
• I can totally understand the question downvote, but why was the answer downvoted? – John Dvorak Mar 16 '15 at 9:45
• @JanDvorak I'm guessing its because it uses comments to make the palindrome, which specifically makes that strategy ok. It's not a very interesting way and is specifically banned in at least one question requiring palindromic code:codegolf.stackexchange.com/q/28190/15599 . Tomek, welcome to programming puzzles and codegolf. I'm upvoting anyway so you have access to our sandbox meta.codegolf.stackexchange.com/q/2140/15599 however I recommend you stick around and answer a few questions before you ask another one. Also, remember to search for similar questions before posting – Level River St Mar 16 '15 at 10:48
• Are functions allowed (instead of whole programs)? – nimi Mar 16 '15 at 21:45
• Can we use a delimiter for the palindrome generated? i.e. neverod -> neverodadoreven (with the a in between) – Rɪᴋᴇʀ Apr 25 '16 at 23:38

Dyalog APL, 6 4

⌽,,⌽


Try it here.

Other solutions:

⌽,⊢⊢,⌽
⌽⊢⊢,⊢⊢⌽


Explanation

They are just:

{⌽((,⍵),(⌽⍵))}
{⌽((,⍵)⊢((⊢⍵),(⌽⍵)))}
{(⌽⍵)⊢((⊢⍵),((⊢⍵)⊢(⌽⍵)))}


Monadic , and ⊢ does nothing on strings. Dyadic , is concatenation. Dyadic ⊢ returns its right operand. And ⌽ is obviously reversion.

• Note that this only works in Dyalog APL. – FUZxxl Apr 8 '15 at 11:05

piet 19x2 = 38

Accepts input until it encounters 0x00. Doesn't terminate, but output will be correct.

• Symmetric: yes; palindromic: ? – Blue Apr 26 '16 at 2:16
• @Blue I don't think it's possible to make a PNG image file palindromic due to the header and footer. Also, PNG compression means that the bytes in the image are almost certainly not palindromic. – Esolanging Fruit Dec 3 '16 at 23:28
• @EsolangingFruit Though one could argue that the image equivalent of a palindrome should be centrosymmetric. – Jonathan Frech Sep 18 '18 at 10:09

APL, 9

⍞←Z,⌽,Z←⍞


Explanation:

       Z←⍞  ⍝ read a line from the keyboard, and store it in Z
,     ⍝ flatten into one-dimensional array (this has no effect here)
⌽      ⍝ reverse
Z,       ⍝ concatenate Z to its reverse
⍞←         ⍝ explicit output (not necessary, but it makes it a palindrome)


CJam, 13 bytes

qL;_-1%1-_;Lq

qL;                 "Read the input, Put an empty array on stack and pop that array";
_-1%             "Now the string is on top, make a copy and reverse the copy";
1-           "Remove occurrences of integer 1 from the reverse string. [no-op]";
_;         "Copy the reversed string and pop it";
Lq       "Put an empty array on stack and read the remaining input. Remaining";
"input will be empty as we already read whole of the input";


Try it online here

or..

GolfScript, 9 bytes

.-1%}%1-.

.                 "Input is already on stack. Make a copy";
-1%              "Reverse the copy";
}             "This marks the beginning of a super comment. Anything after this in the";
"code is a comment";
%1-.         "no-op comment";


Try it here

• I think you've found a bug in the GolfScript parser with your "super-comment". Mind you, an ordinary # comment would work just as well there. – Ilmari Karonen Mar 16 '15 at 16:47
• @IlmariKaronen Its not me, } has been known to be a super comment since ages :) – Optimizer Mar 16 '15 at 16:51

C++, 162 bytes

#include<cstdio>//
main(){int c=getchar();if(c>0)putchar(c),main(),putchar(c);}//};)c(rahctup,)(niam,)c(rahctup)0>c(fi;)(rahcteg=c tni{)(niam
//>oidtsc<edulcni#


C, 117 bytes

main(c){c=getchar();if(c>0)putchar(c),main(),putchar(c);}//};)c(rahctup,)(niam,)c(rahctup)0>c(fi;)(rahcteg=c{)c(niam

• god bless the two slashes lol – Abr001am Apr 26 '16 at 19:24

a b fa=fa<|>b
fa=reverse>>=a
main=interact fa
niam=main
af tcaretni=niam
a=>>esrever=af
b>|<af=af b a


This must be run with the Control.Applicative module in scope, which can be set via the ghci init file .ghci: :m Control.Applicative (-> +22 bytes).

No comment trick, just 7 functions where 4 of them are never called.

If functions (instead of programs) are allowed:

a b fa=fa<|>b
f=reverse>>=a
a=>>esrever=f
b>|<af=af b a


Usage f "qwer"-> "qwerrewq"

Edit: the previous version was just wrong.

Pyth, 11 bytes

+z_z " z_z+


In Pyth, anything preceding with a space is not printed. So we simply add the negative of the string to itself, put a space, start a string and mirror the left side of the quote"

Try it online here

Ruby, 44

s=gets p
s+=s.reverse||esrever.s=+s
p steg=s


Takes a multiline string as input from stdin, outputs a Ruby representation of that string concatenated to its reverse. Could trim a character by replacing || with # to comment out the dead code on the second line.

• s=gets p!=p steg=s – CalculatorFeline Apr 25 '16 at 22:17
• ...true, I have no idea what I meant by that. – histocrat Apr 25 '16 at 22:23

Jolf, 9 bytes

Try Here

aη+i_i+ηa


Explanation: I only just started Jolf and I don't think I'm explaining this properly.

aη         alert function, arity of the function can't be reduced by 1 so it stays at 1
+i_i     concatenate the input with the reversed input
+η   arity of the add reduced by 1, it just takes the following character (a)
a  returns the input

• Welcome to PPCG! I saw your other answer, and I fondly appreciate you using this language! It is my own inventions, I hope you like it :) This is a really nice solution, very well done! I like the way you used η in the solution, very well done. You can save two bytes by eliminating the mu, as: a+i_i+a. (Jolf also has implicit input to fill in the rest of the arguments, but this isn't a problem since only one input is given at a time.) I would keep your original solution in the answer, still. – Conor O'Brien Apr 26 '16 at 19:15
• @Cᴏɴᴏʀ O'Bʀɪᴇɴ Thanks! I just chose a golfing language that didn't seem too scary and jumped in, I've been enjoying figuring it out. I was trying to figure out where the η came from and realized that it was from trying to fix my starting point of +i_i+. Thanks for the info! – swells Apr 26 '16 at 19:31

PowerShell, 67

$args|%{$_+-join$_[$_.Length..0]}#}]0..htgneL._$[_$nioj-+_${%|sgra$


Try it online

As suggested by @mazzy the code can be shortened by 12 bytes when using a static range. This, however, limits the input length to 9KBytes. Theoratically 9MBytes would be possible but it would slow down the code significantly.

$args|%{$_+-join$_[9kb..0]}#}]0..bk9[_$nioj-+_${%|sgra$

• Alternative 67 bytes: param($s)$s+-join$s[$s.Length..0]#]0..htgneL.s$[s$nioj-+s$)s$(marap – mazzy Sep 17 '18 at 13:57
• if input string length less then 9Kbytes then $args|%{$_+-join$_[9Kb..0]}#}]0..bK9[_$nioj-+_${%|sgra$ (55 bytes) – mazzy Sep 17 '18 at 14:01

Fuzzy Octo Guacamole, 17 bytes

FOG is newer than this challenge, so this is non-competing.

^dz''sjX@Xjs''zd^


Alt solution in 19 bytes:

^Czs''.jX@Xj.''szC^


They both take input, duplicate and reverse, and join the stack.

Explanation:

^dz''sj@js''zd^
^                # Get input
d               # Duplicate ToS (input)
z              # Reverse ToS
''            # Push empty string (for joining separator)
s           # Move the empty string to the inactive stack
j          # Join the active stack with the top of the inactive stack as the delimiter and push the result.
X         # Print the ToS
@        # End the program
Xjs''zd^  # Backwards version of the beginning.

• Also, noncompeting :P – Conor O'Brien Apr 25 '16 at 23:56
• @CᴏɴᴏʀO'Bʀɪᴇɴ oops. :P – Rɪᴋᴇʀ Apr 26 '16 at 1:54

tinyBF, 40

|=||==>|=|=|=+|=>==||==>=|+=|=|=|>==||=|


My first thought was Brainfuck, but it's impossible to match the braces... fortunately tinyBF has simpler flow control.

No comments, it takes a null terminated string as input and returns the result in a null terminated string. You can test it here, just be forewarned that it doesn't halt (although Firefox at least prompts to stop the unresponsive script).

Commented:

|=|                        Retrieve a byte of input.
|                          Positive (opening) bracket.
==                      Output the byte.
>                       Move the pointer in positive direction.
|=|                     Retrieve a byte of input.
=                       Switch direction to negative.
|                          Negative (closing) bracket.
=                          Switch direction.
+                          Increment byte to execute return loop.
|                          Opening bracket.
=>                      Move the pointer in negative direction.
==                      Output the byte.
|                          Closing bracket.
|=|                        Output the null terminator.
|==>|=|=|=+|=>==|          ...and keep null terminating it just to be sure.


Note that if you encode it into 2 bit instructions, it cuts the size to 10 bytes (wouldn't be a palindrome).

Python 3, 59 bytes

a=input()#
print(a+a[::-1])#([1-::]a+a)tnirp
#()tupni=a


I tried my best to find a solution that only used one line but I had no luck.

Python 3, 79 bytes

a=input()#()tupni=a#
print(a+a[::-1])#([1-::]a+a)tnirp
#a=input()#()tupni=a


My original attempt in which every line is a palindrome. I don't think that it is necessary for this challenge, but I included it just in case.

• One-line but even longer (73, since lambda is so long): print((lambda a:a+a[::-1])(input()))#)))(tupni()]1-::[a+a:a adbmal((tnirp – no1xsyzy Sep 18 '18 at 5:04
• Very nice. I'm less familiar with lambdas but I'm slowly getting used to them. Thanks for sharing. – Noomann Sep 18 '18 at 19:17

Vitsy, 9 bytes

z:Zr?rZ:z
z          Grab all string input from the command line arguments.
:         Duplicate this stack.
Z        Print all elements in this stack as a string.
r       Reverse (reverses an empty stack).
?      Go right a stack.
r     Reverse (reverses the input).
Z    Print all elements in this stack as a string.
:   Duplicate the stack (duplicates an empty stack).
z  Grab all input from the command line (the command line arguments stack is already empty).


Try it online!

Befunge, 37 bytes

~:0!#v_:,
>:#,_@_,#:>
,:_v#!0:~


Try it online!

The top line pushes and prints every character of input. The second line (before the @) prints the stack in reverse, but we enter at the contional _ to consume the -1 generated when finish reading input. The other half of the code (including those ugly trailing newlines) makes the source a palindrome, but nevers runs.

C# (33 32 + 1) * 2 = 68 66 bytes

saved 2 bytes to the use of .Aggregate()

s=>s+s.Aggregate("",(a,b)=>b+a);//;)a+b>=)b,a(,""(etagerggA.s+s>=s


Oh the good old lambda, you can catch it with

Func<string, string> f=<lambda here>


and then call it with

f("neverod")


Perl, 45 bytes

;print$_=<>,~~reverse;m;esrever~~,><=_$tnirp;


Pretty straightforward, prints the input ($_=<>) followed by the reverse of it. reverse returns $_ because we're using it in scalar context by prefixing with ~~. Then we match (m// using ; as delimiter), in void context, against the reverse of the script.

If we can guarrantee we won't have to create a palindrome of esrever,><=_$tnirp we can shorten the code to 43 bytes: g.print$_=<>,reverse.m.esrever,><=_$tnirp.g  Usage echo -n 'neverod' | perl -e 'g.print$_=<>,reverse.m.esrever,><=_$tnirp.g' neveroddoreven  Perl, 26 bytes Includes 25 bytes code + 1 for -p. $_.=reverse;m;esrever=._$ I don't think this is valid since it requires the -p flag which I don't think can be easily combined into the script contents to make a true palindrome. Pretty much the same calls as above, except it relies on the fact that -p also adds a ; behind the scenes (on newer Perls...) to close the m//. Usage echo -n 'neverod' | perl -pe ';$_.=reverse;m;esrever=._$;' neveroddoreven  Pyth, 15  k k+ z_z +k k  Notice the space at the beginning and at the end. Quite annoying task in Pyth. z_z prints the desired palindrome, but it prints z (the input string) and _z the inverse on two different lines. + combines the two words, but + at the end requires two new statements at the end (and at the beginning). I choose k and k, which are just empty strings. Then a lot of white space, which suppresses printing (and printing empty spaces, which generate of course line breaks). Since the white space suppresses every output except the +z_z, you can replace the ks and literal with arity 0. E.g. 1 2+ z_z +2 1 or T Z+ z_z +Z T. Try it online. • I have an 11 one in Pyth, which I did not post yet coz I thought you will surely beat it ;) – Optimizer Mar 16 '15 at 22:55 Javascript, 137 bytes I'm not using the "comment trick" but I am using the escaped quotation mark trick lol. "a\"};))''(nioj.)(esrever.)''(tilps.b(tacnoc.b nruter{)b(a noitcnuf";function a(b){return b.concat(b.split('').reverse().join(''));};"\a"  • I don't think this counts; the two central chars are ";. Adding a ; as the last char inside the string should fix this. – ETHproductions Nov 3 '16 at 15:01 • As it stands this answer is invalid. Please either fix it or remove it. – Jonathan Frech Sep 18 '18 at 15:08 JavaScript, 58 bytes p=>p+[...p].reverse().join//nioj.)(esrever.]p...[+p>=p  PHP, 28+1+28=57 bytes <?=($x=$argv[1]).strrev($x);#;)x$(verrts.)]1[vgra$=x\$(=?<


takes input from command line argument. quote for multi-word, escape newlines for multi-line.

Python 2, 51 bytes

s=input();print s+s[::-1]#]1-::[s+s tnirp;)(tupni=s


I'm surprised no-one thought of this! Needs quoted input (' or "). If functions were allowed, I could have done this for 37 bytes instead:

lambda x:x+x[::-1]#]1-::[x+x:x adbmal


C++14, 152 116 bytes

As unnamed lambda, assumes s to be string

[](auto s){decltype(s)r;for(auto c:s){r=c+r;}return s+r;}//};r+s nruter};r+c=r{)s:c otua(rof;r)s(epytlced{)s otua(][


Old solution:

[](auto s){auto r=s;for(auto p=s.rbegin()-1;++p!=s.rend();r+=*p);return r;}//};r nruter;)p*=+r;)(dner.s=!p++;1-)(nigebr.s=p otua(rof;s=r otua{)s otua(][


Usage:

auto f=[](auto s){decltype(s)r;for(auto c:s){r=c+r;}return s+r;};

main(){
string a="123456789";
cout << f(a) << endl;
}


05AB1E, 5 bytes

Â«q«Â


Try it online.

Explanation:

Â        # Bifurcate (short for Duplicate & Reverse) the (implicit) input
#  i.e. "neverod" → "neverod" and "doreven"
«       # Concat both together
#  i.e. "neverod" and "doreven" → "neveroddoreven"
q      # Exit the program (and implicitly output the concatted result)
«Â    # No-ops


Or alternatively:

R«q«R


Try it online.

Where R is reverse, and the « takes the input implicitly again to concat with.

NOTE: If we are allowed to output neverodoreven for the input neverod, which is still a palindrome, it can be done in 1 byte instead with the palindromize builtin:

û


Try it online.

x86-64 Assembly (Microsoft x64 calling convention), 89 bytes:

80 39 00 48 8B D1 4C 8B C1 74 0B 48 FF C2 49 FF C0 80 3A 00 75 F5 48 FF CA 8A 02 41 88 00 48 8B C2 48 FF CA 49 FF C0 48 3B C1 77 ED C3 ED 77 C1 3B 48 C0 FF 49 CA FF 48 C2 8B 48 00 88 41 02 8A CA FF 48 F5 75 00 3A 80 C0 FF 49 C2 FF 48 0B 74 C1 8B 4C D1 8B 48 00 39 80


Disassembled:

 0000000000000000: 80 39 00           cmp         byte ptr [rcx],0
0000000000000003: 48 8B D1           mov         rdx,rcx
0000000000000006: 4C 8B C1           mov         r8,rcx
0000000000000009: 74 0B              je          0000000000000016
000000000000000B: 48 FF C2           inc         rdx
000000000000000E: 49 FF C0           inc         r8
0000000000000011: 80 3A 00           cmp         byte ptr [rdx],0
0000000000000014: 75 F5              jne         000000000000000B
0000000000000016: 48 FF CA           dec         rdx
0000000000000019: 8A 02              mov         al,byte ptr [rdx]
000000000000001B: 41 88 00           mov         byte ptr [r8],al
000000000000001E: 48 8B C2           mov         rax,rdx
0000000000000021: 48 FF CA           dec         rdx
0000000000000024: 49 FF C0           inc         r8
0000000000000027: 48 3B C1           cmp         rax,rcx
000000000000002A: 77 ED              ja          0000000000000019
000000000000002C: C3                 ret
000000000000002D: ED                 in          eax,dx
000000000000002E: 77 C1              ja          FFFFFFFFFFFFFFF1
0000000000000030: 3B 48 C0           cmp         ecx,dword ptr [rax-40h]
0000000000000033: FF 49 CA           dec         dword ptr [rcx-36h]
0000000000000036: FF 48 C2           dec         dword ptr [rax-3Eh]
0000000000000039: 8B 48 00           mov         ecx,dword ptr [rax]
000000000000003C: 88 41 02           mov         byte ptr [rcx+2],al
000000000000003F: 8A CA              mov         cl,dl
0000000000000041: FF 48 F5           dec         dword ptr [rax-0Bh]
0000000000000044: 75 00              jne         0000000000000046
0000000000000046: 3A 80 C0 FF 49 C2  cmp         al,byte ptr [rax+FFFFFFFFC249FFC0h]
000000000000004C: FF 48 0B           dec         dword ptr [rax+0Bh]
000000000000004F: 74 C1              je          0000000000000012
0000000000000051: 8B 4C D1 8B        mov         ecx,dword ptr [rcx+rdx*8-75h]
0000000000000055: 48 00 39           add         byte ptr [rcx],dil
0000000000000058: 80


Note that the code after the ret instruction at 2C is unreachable so it doesn't matter that it's nonsense

Japt, 4 bytes

êêêê


Try it online!

How it works

U.ê("ê".ê("ê"))  Transpiled to JS

.ê("ê")   String.ê(string): true if this is palindrome
"ê".ê("ê")   true (treated same as 1)
U.ê(          )  String.ê(number): palindromify
"abc"->"abccba" if number is odd, "abcba" otherwise
true is odd number, so we achieve the desired function


Alternative 4 bytes

pwwp


Try it online!

How it works

U.p("w".w("p"))  Transpiled to JS
"w".w(   )   Reverse of "w" ("p" is ignored)
U.p("w")         Append U.w(), which is reverse of U, to the right of U


Backhand, 33 27 bytes

iH~0}|{<:: oi]io ::<{|}0~Hi


Try it online!

Unlike a lot of the solutions here, this one actually does use the palindromised code!

Explanation:

i  0 |{      Get the first character and enter the loop
:  o    Output the character while preserving it
i  :     Get input and duplicate it
<{  Turn around
]         Increment the copy to check if EOF
}| <    Loop again if not EOF
~   If EOF, pop the extra copy of EOF
H    Terminate, printing the contents of the stack.


Altogether, the unexecuted instructions are:

       :   i  o :   |}0~Hi