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.
Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It only takes a minute to sign up.
Sign up to join this communityCreate 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.
⌽,,⌽
Other solutions:
⌽,⊢⊢,⌽
⌽⊢⊢,⊢⊢⌽
They are just:
{⌽((,⍵),(⌽⍵))}
{⌽((,⍵)⊢((⊢⍵),(⌽⍵)))}
{(⌽⍵)⊢((⊢⍵),((⊢⍵)⊢(⌽⍵)))}
Monadic ,
and ⊢
does nothing on strings. Dyadic ,
is concatenation. Dyadic ⊢
returns its right operand. And ⌽
is obviously reversion.
Accepts input until it encounters 0x00. Doesn't terminate, but output will be correct.
⍞←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)
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";
or..
.-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";
#
comment would work just as well there.
\$\endgroup\$
– Ilmari Karonen
Mar 16 '15 at 16:47
}
has been known to be a super comment since ages :)
\$\endgroup\$
– Optimizer
Mar 16 '15 at 16:51
#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#
main(c){c=getchar();if(c>0)putchar(c),main(),putchar(c);}//};)c(rahctup,)(niam,)c(rahctup)0>c(fi;)(rahcteg=c{)c(niam
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.
+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"
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.
Newer language, non-competing
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
η
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.
\$\endgroup\$
– Conor O'Brien
Apr 26 '16 at 19:15
$args|%{$_+-join$_[$_.Length..0]}#}]0..htgneL._$[_$nioj-+_${%|sgra$
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$
param($s)$s+-join$s[$s.Length..0]#]0..htgneL.s$[s$nioj-+s$)s$(marap
\$\endgroup\$
– mazzy
Sep 17 '18 at 13:57
$args|%{$_+-join$_[9Kb..0]}#}]0..bK9[_$nioj-+_${%|sgra$
(55 bytes)
\$\endgroup\$
– mazzy
Sep 17 '18 at 14:01
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.
|=||==>|=|=|=+|=>==||==>=|+=|=|=|>==||=|
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).
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.
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.
lambda
is so long): print((lambda a:a+a[::-1])(input()))#)))(tupni()]1-::[a+a:a adbmal((tnirp
\$\endgroup\$
– InQβ
Sep 18 '18 at 5:04
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).
~:0`!#v_:,
>:#,_@_,#:>
,:_v#!`0:~
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.
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")
;print$_=<>,~~reverse;m;esrever~~,><=_$tnirp;
Pretty straightforward, print
s 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
echo -n 'neverod' | perl -e 'g.print$_=<>,reverse.m.esrever,><=_$tnirp.g'
neveroddoreven
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//
.
echo -n 'neverod' | perl -pe ';$_.=reverse;m;esrever=._$;'
neveroddoreven
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 k
s and literal with arity 0. E.g. 1 2+ z_z +2 1
or T Z+ z_z +Z T
.
Try it online.
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"
";
. Adding a ;
as the last char inside the string should fix this.
\$\endgroup\$
– ETHproductions
Nov 3 '16 at 15:01
p=>p+[...p].reverse().join``//``nioj.)(esrever.]p...[+p>=p
<?=($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.
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
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;
}
«q«Â
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
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:
û
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
êêêê
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
pwwp
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
iH~0}|{<:: oi]io ::<{|}0~Hi
Unlike a lot of the solutions here, this one actually does use the palindromised code!
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
+ Q_Q +
Uses implicit variables at the end of the program, which was not a feature when the other Pyth answers here were posted.
neverod
->neverodadoreven
(with thea
in between) \$\endgroup\$ – Rɪᴋᴇʀ Apr 25 '16 at 23:38