Palindrome polyglot

15

2

Your task is to write a program that runs in two different languages, and does the following:

  • In one language, it palindromizes a given string.
    • Take the string. abcde
    • Reverse the string. edcba
    • Remove the first character. dcba
    • Glue it onto the original string. abcdedcba
  • In another language, it depalindromizes a given string.
    • Take a string palidromized by the above method. abcdedcba
    • Get the characters from the start to the middle. abcde

Remember, this is , so the code with the fewest characters (not bytes) wins.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language 1/Language 2, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby/Python, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl/C, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish)/Python, 121 bytes

var QUESTION_ID=98776,OVERRIDE_USER=12537;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

Oliver Ni

Posted 2016-11-06T17:50:38.197

Reputation: 9 650

@LuisMendo One second... – Oliver Ni – 2016-11-06T18:09:27.007

@LuisMendo Okay, I have updated the quesiton – Oliver Ni – 2016-11-06T18:09:56.923

Will the string ever contain newlines? – Erik the Outgolfer – 2016-11-06T18:41:37.233

Can the input format be different in the two languages? Like a string with enclosing quotes or without them – Luis Mendo – 2016-11-06T22:39:41.990

@LuisMendo Yes. – Oliver Ni – 2016-11-06T23:33:49.513

This is sort of coming down to finding the language that can depalindromize with the least code, then combining it with ¹û (05AB1E) or ŒB (Jelly) (or in Japt) – ETHproductions – 2016-11-07T16:13:41.373

Answers

14

05AB1E / MATL, 10 9 characters

9LQ2/)%¹û

In 05AB1E this palindromizes. In MATL it depalindromizes.

Explanation in 05AB1E

This part of the code does nothing (globally):

9L    Pushes array [1, 2, ... 9]
Q     Consumes the array, takes the input implicitly, and produces no output
2/    With no further input to take implicitly, this gives no output
)     Wrap stack into an array: gives an empty array
%     Consumes that array and, with no further input to take implicitly, gives no ouput 

This is the part that does the work:

¹     Push input again
û     Palindromize. Implicitly display

Explanation in MATL

This is the part that does the work:

9L    Push array [0, 1j]
Q2/   Add 1, divide by two: transforms into [1/2, (1+1j)/2]
)     Use as index into implicit input. [1/2, (1+1j)/2] is interpreted as
      1/2:(end+1)/2, which is rounded to 1:(end+1)/2. So this takes elements
      from first to half, including both. Implicitly display

This is ignored:

%¹û   Everything after '%' is a comment

Luis Mendo

Posted 2016-11-06T17:50:38.197

Reputation: 87 464

12

05AB1E / Jelly, 6 characters

Palindromizes in 05AB1E.
Depalindromizes in Jelly.

œs2Ḣ¹û

Try it in 05AB1E

05AB1E Explanation

œ       # compute powerset of input
 s      # swap (does nothing)
  2     # push 2
   Ḣ    # does nothing
    ¹û  # palindromize input

Try it in Jelly

Jelly Explanation

œs2     # split input in 2 chunks (first chunk is larger for odd length strings)
   Ḣ    # head, take first
    ¹û  # does nothing

Emigna

Posted 2016-11-06T17:50:38.197

Reputation: 50 798

6

Python 3 / JavaScript, 83 chars

Saved 2 bytes thanks to @LevitatingLion

1//2;x=input();print(x+x[-2::-1]);"""
x=prompt();alert(x.slice(0,-x.length/2))//"""

Python palindromizes, JavaScript depalindromizes.

I tried keeping more code constant between the two, but I couldn't figure out a good way to sneak .slice into Python. Here's an alternate method:

1//2;prompt=input,alert=print
x=prompt();1//2;x+=x[-2::-1]);"""
x=x.slice(0,-x.length/2))//"""
alert(x)

ETHproductions

Posted 2016-11-06T17:50:38.197

Reputation: 47 880

You can replace x[::-1][1:] with x[-2::-1] to save two chars. – LevitatingLion – 2016-11-07T17:21:18.367

@LevitatingLion Thank you! I'd tried to figure out how to combine the two slices, but nothing seemed to work. – ETHproductions – 2016-11-07T17:23:38.780

5

Scala / Javascript, 106 bytes

/*\u002A/print(args(0)+args(0).reverse.tail)//*/
/*/**/
alert((s=prompt()).slice(0,-s.length/2))//\u000A*/

Palindromizes in scala and depalindromizes in javascript.

Try it on ideone (scala) - Warning: wrong syntax highlighting

Try it on jsfiddle (javascript).

Explanation:

Scala, like java, processes unicode escapes before everything else, so scalac sees the code like this:

/**/                                //\u002A is as asterisk, results in an empty block comment
print(args(0)+args(0).reverse.tail) //scala code
//*/                                //a line comment
/*                                  //scala supports nested block comments, so this comment...
  /*
  */
  alert((s=prompt()).slice(0,-s.length/2)) 
  //                                  //\u000A (newline) inserted here
*/                                  //...ends here

The javascript gets parsed like this:

/*\u002A/print(args(0)+args(0).reverse.tail)//*/ //block comment
/*                                               //a block comment...
  /*
*/                                               //...ending here, no nesting
alert((s=prompt()).slice(0,-s.length/2))         //code
//\u000A*/                                       //line comment

corvus_192

Posted 2016-11-06T17:50:38.197

Reputation: 1 889

4

CJam / MATL, 18 characters

r_W%(;
"j9LQ2/)%";

In CJam this palindromizes. In MATL it depalindromizes.

Explanation in CJam

Working part:

r           Read string
_           Duplicate
W%          Reverse
(;          Remove first element

Dummy part:

"j9LQ2/)%"  Push this string
;           Remove it from the stack
            Implicitly display both strings obtained previously

Explanation in MATL

Dummy part:

r           Push random number between 0 and 1
_           Negate
W           2 raised to that
%(;  Comment (ignored)

Working part:

"           For each element in the array at the top of the stack. Since it is a number,
            which is the same as a length-1 array, the following is executed once
  j         Input string
  9L        Push array [0, 1j]
  Q2/       Add 1, divide by 2: transforms into [1/2, (1+1j)/2]
  )         Use as index. [1/2, (1+1j)/2] is interpreted as 1/2:(end+1)/2, which is
            rounded to 1:(1+end)/2. So this takes elements from first to half,
            including both

Another dummy part:

   %";      Comment (ignored)
            Implicitly display the previously obtained string

Luis Mendo

Posted 2016-11-06T17:50:38.197

Reputation: 87 464

4

Jelly / CJam, 15 14 chars

q_,2./m]<e#¶ŒB

-1 char thanks to 42545 (ETHproductions)

Try it online! (Jelly) (Palindromization)

CJam interpreter (Depalindromization)

Jelly explanation:

In Jelly, is the same as \n, so this is what Jelly sees:

q_,2./m]<e#
ṖṚṭ

ṖṚṭ         Main link. Arguments: z
Ṗ           Pop
 Ṛ          Reverse
  ṭ         Append
   ⁸        (implicit) z

CJam explanation:

In CJam, everything after e# on a line is a comment. So, this is what CJam sees:

q_,2./m]< Code
q         All input
 _        Duplicate
  ,       Length
   2.     2.0
     /    Float division
      m]  Ceil
        < Take

Erik the Outgolfer

Posted 2016-11-06T17:50:38.197

Reputation: 38 134

@ETHproductions Whoops, I forgot it! It's called "bounce", that's why. – Erik the Outgolfer – 2016-11-07T16:09:51.053

4

/ Javascript ES6, 55 chars

this._?Σ(`ï+ï.Ħ⬮.Đ1`):(x=prompt()).slice(0,-x.length/2)

Try it here (ES6 browsers only).

Palindromizes in , depalindromizes in Javascript ES6.

I though this was going to be easy, since compiles to ES6 and most of ES6 can be run in . Apparently, I'm completely wrong.

Explanation

this._ checks to see if variable _ exists in the global scope; uses Lodash and therefore has _ stored, but pure ES6 doesn't.

The segment - Σ(`ï+ï.Ħ⬮.Đ1`) - evaluates from string the code that palindromizes input. Normally, the code would be ï+ïĦ⬮Đ1, but I put the dots in to make the compiler happy.

The Javascript segment - (x=prompt()).slice(0,-x.length/2) - depalindromizes a string from a prompt.


I was going to use a function (so I didn't have to deal with prompt), but 's evaluation function didn't like that, so I used prompt and no function to make the compiler happy.

Mama Fun Roll

Posted 2016-11-06T17:50:38.197

Reputation: 7 234

Wow, the compiler's picky. – HyperNeutrino – 2016-11-06T20:06:50.437

4

JavaScript ES6 / JavaScript ES3, 143 bytes

function(x){'use strict';function a(){return x+x.split('').reverse().slice(1).join('')}{function a(){return x.slice(0,-x.length/2)}}return a()}

Palindromizes in JavaScript ES6, depalindromizes in JavaScript ES3. Non competing, it's just a try to make a polyglot for two versions of the same language.

In ES3 functions are allowed in blocks, but as blocks don't define scopes the new function just replaces the first function. In ES5 strict mode it fails because it don't allow functions to be defined in blocks. In ES6 it's allowed and, because blocks now define scopes, the first function isn't replaced.

Tested in Internet Explorer 5 (emulated) for ES3 and Node.JS and Firefox for ES6.

Gustavo Rodrigues

Posted 2016-11-06T17:50:38.197

Reputation: 261

4

Perl / JavaScript, 73 bytes

Perl returns a palindrome and JavaScript 'de-palindromizes' the input string.

s=prompt();console.log(s.slice(0,-s.length/2));eg=1;t=eg;s=$=reverse$_=eg

JavaScript

Assumes the string is a valid palindrome already.

All the work happens in the first section:

s=prompt();console.log(s.slice(0,-s.length/2));

Stores input in s, then returns the first half (rounded-up) of the string. The rest of the script is pointless variable assignments:

eg=1;t=eg;s=$=reverse$_=eg

Try it here:

s=prompt();console.log(s.slice(0,-s.length/2));eg=1;t=eg;s=$=reverse$_=eg

Perl

Must be run with -pl, eg:

perl -ple 's=prompt();console.log(s.slice(0,-s.length/2));eg=1;t=eg;s=$=reverse$_=eg' <<< 'test'
# returns testtset

The code is basically two substitutions (s///), but using = as the delimiter instead of /:

s/prompt();console.log(s.slice(0,-s.length\/2));eg/1;t/eg;s/$/reverse$_/eg

The first, replacing prompt();console.log(s.slice(0,-s.length\/2));eg (which, admittedly will mess up your string if it contains something like "prompt;console.logs.slice0,-s.length/2;eg"...) with 1;t which is evaled, returning t, the second replaces the end of the string ($) with reverse$_ which is then also evaled and appends the original source string reversed.

Try it online!

Dom Hastings

Posted 2016-11-06T17:50:38.197

Reputation: 16 415

3

Python 2 / Nim, 76 74 bytes

#[
s=input();print s+s[-2::-1]#let s=stdin.readLine;echo s[0..s.len div 2]

Palindromizes in Python, depalindromizes in Nim. Abuses comment syntax.

Python and Nim both use # for comments. Python doesn't support block comments at all (except for multiline strings with """), but Nim does with #[ comment ]#.

We abuse this to comment out the Python (at the beginning) for Nim, then use the trailing ] in the Python to start the Nim code, looking like a comment for Python.

The Python code requires its input surrounded with quotes. The Nim code doesn't have this restriction.

Tested on Python 2.7.8 and Nim 0.14.2.

Ideone it! -- Python 2, palindromizing

Ideone it! -- Nim, depalindromizing Apparently the version of Nim Ideone uses (0.11.2) doesn't support multiline comments. Works on Nim 0.14.2.

Copper

Posted 2016-11-06T17:50:38.197

Reputation: 3 684

2

Erik the Outgolfer

Posted 2016-11-06T17:50:38.197

Reputation: 38 134

2

05AB1E/V, 14 bytes

û,ò"Bx$xh|ò"bP

Try it online!

Palindromizes in 05AB1E

Try it online!

Depalindromizes in V, using this answer from DrMcMoylex.

Magic Octopus Urn

Posted 2016-11-06T17:50:38.197

Reputation: 19 422

2

Japt / JavaScript, 63 chars

Lesson of the day: Japt/JavaScript polyglots are always a bad idea...

$Oq=1;$Oq &&0
alert(($U=prompt()).slice(0*$U,-$U.length/2));$Uê

JavaScript

The first line sets the variable $Oq to 1, then performs a no-op with $Oq &&0.

The second line prompts the user for an input string, assigning it to the variable $U, then slices it from index 0*$U (always 0) to index -$U.length/2. This performs the necessary depalindromization; the result is then alerted. The program ends on a ReferenceError because variable $Uê is not defined.

Japt

In Japt, anything between dollar signs is inserted directly into the transpiled source code. Other than that, each lowercase letter transpiles to e.g. .q(, unless the previous char was another lowercase letter, in which case it becomes "q". A space is transpiled to ), and all missing parens are automatically added. The above program transpiles roughly to:

Oq=1;O.q()&&0
.a("l".e("r".t((U=prompt()).slice(0*U,-U.length/2))));U.ê()

This is then executed as JavaScript. Oq=1; sets the variable Oq to 1. This is never used again, so it's a no-op. O.q() is a function that clears STDOUT and returns undefined; this is falsy, so the entire &&0 .a("l".e(... part is not executed.

The only part that really matters is U.ê(). Implicit input puts the input string in U, .ê() turns it into a palindrome, and implicit output sends the result to STDOUT.


If function entries are allowed, the following will work for 34 chars:

X=>($X=X).slice(0,-X.length/2);$Uê

The first part defines an ES6 function, but it's still a full program in Japt. Test it online!

ETHproductions

Posted 2016-11-06T17:50:38.197

Reputation: 47 880

2

Java / Brainfuck, 71 bytes

/*+[,>]<[<]>[.>]<<[.<][*/a->a.substring(0,Math.ceil(a.length()/2d));//]

Palindromizes in BF, depalindromizes in Java.

For the sake of clarity, this is what matters to the BF interpreter:

+[,>]<[<]>[.>]<<[.<][->,..]

where the last loop containing characters from the Java lambda is skipped because the pointer points to a null character at that point.

user8397947

Posted 2016-11-06T17:50:38.197

Reputation: 1 242

0

05AB1E / Java 8, 102 chars

//¹ûq
interface M{static void main(String[]a){System.out.print(a[0].substring(0,a[0].length()/2+1));}}

Palindromize in 05AB1E.
Depalindromize in Java 8.

Explanation 05AB1E:

//     # No-ops
¹      # First input
 û     # Palindromize it
  q    # Terminate the program
interface M{static void main(String[]a){System.out.print(a[0].substring(0,a[0].length()/2+1));}}
       # No-ops

Explanation Java 8:

//¹ûq                           // No-ops
interface M{                    // Class
  static void main(String[]a){  //  Mandatory main-method
    System.out.print(           //   Print to STDOUT:
      a[0].substring(0,         //    The substring of the input-argument from index 0 to
        a[0].length()/2+1));}}  //    the length of the input integer-divided by 2 plus 1

Kevin Cruijssen

Posted 2016-11-06T17:50:38.197

Reputation: 67 575