title: Perform gravity sort

text:
# Question
Title: Perform gravity sort
# Challenge

Given a list of integers, show how gravity sort would be done.

# Gravity Sort

In gravity sort, imagine the numbers as rows of asterisks. Then, everything falls, and the new rows will be obviously sorted. Let's look at an example:

`[2, 7, 4, 6]`:

```
**
*******
****
******
-------
**
****
*******
******
-------
**      | 2
****    | 4
******  | 6
******* | 7

```

Notice that this is pretty much just parallelized bubble sort.

# Exact Specs

On each iteration, starting from the top row, take every asterisk from the row that doesn't have an asterisk below it, and move it down a row. Keep doing that until the list is sorted.

# Input

Input will be a list of strictly positive integers.

# Output

For the output, you must output each step. You can choose any two non-whitespace printable ASCII characters, one to be the "asterisks", and one to be the separating "dashes". The rows of asterisks must be separated with a standard newline of some sort (e.g. `\n` or `\r\f`). The row of dashes must be at least the width of the widest row (otherwise your asterisks are going to fall too far down!). A row of dashes at the very bottom is optional. A trailing newline at the end is permitted. Trailing spaces on each line are permitted.

# Test Cases

input will be represented as a list, then output will be listed immediately below. Test cases are separated by a double-newline.

```
[4, 3, 2, 1]
****
***
**
*
----
***
** *
* *
**
----
**
* *
** *
***
----
*
**
***
****

[6, 4, 2, 5, 3, 1]
******
****
**
*****
***
*
------
****
**  **
****
***
*  **
***
------
**
****
*** **
*  *
***
*****
------
**
***
*  *
*** **
****
*****
------
**
*
***
****
******
*****
------
*
**
***
****
*****
******

[8, 4, 2, 1]
********
****
**
*
--------
****
**  ****
* **
**
--------
**
* **
**  ****
****
--------
*
**
****
********

[2, 7, 4, 6]
**
*******
****
******
-------
**
****
*******
******
-------
**
****
******
*******

```

Please feel free to correct my test cases if they're wrong, I made them by hand :)

Note: Do not output the sorted list at the end. :)

# Scoring

All of your programs will be written on top of each other. You wouldn't want pieces of your program to fall down, so make sure you have the shortest code!

# Answer
> 9 votes
# Pyth, 27 bytes

```
jsCM.u:R"v "" v"N+R\-.t*L\v

```

Try it online!

# Answer
> 5 votes
# Perl 5, 118 bytes

115 bytes of code + `-pla` flags.

```
\@X[$_]for@F;s%\d+ ?%Y x$&.$"x($#X-$&).$/%ge;while(/Y.{$#X} /s){print$_,_ x$#X;1while s/Y(.{$#X}) /X$1b/s;y/bX/Y /}

```

Try it online!

It seems a bit too long. But again, dealing with multiline strings with regex is usually not easy.

I'm using `Y` instead of `*` and `_` instead of `-`.

# Answer
> 4 votes
# Octave, 104 bytes

```
b=(1:max(L=input("")))<=L;do;disp(" *-"([b;max(b)+1]+1))until b==(b=imerode(b,k=[1;1])|imdilate(b,k)~=b)

```

\*Requires image package.

Try it online!

Explanation:

```
input = [8 ;4 ;2 ;1]

L = input('');                    %input list
b=(1:max(L))<=L;                  % generate matrix of 0s and 1s as indexes of asterisks

b =

  1  1  1  1  1  1  1  1
  1  1  1  1  0  0  0  0
  1  1  0  0  0  0  0  0
  1  0  0  0  0  0  0  0
do;
    disp(' *-'([b;max(b)+1]+1))  %display asterisks and dashes

    E = imerode(b,k=[1;1]);      %morphological erosion
    E =

      1  1  1  1  0  0  0  0
      1  1  0  0  0  0  0  0
      1  0  0  0  0  0  0  0
      1  0  0  0  0  0  0  0

    D = imdilate(b,k);           %morphological dilation
    D =

      1  1  1  1  1  1  1  1
      1  1  1  1  1  1  1  1
      1  1  1  1  0  0  0  0
      1  1  0  0  0  0  0  0

    b_temp = E | (D~=b)          %intermediate result
    b_temp =

      1  1  1  1  0  0  0  0
      1  1  0  0  1  1  1  1
      1  0  1  1  0  0  0  0
      1  1  0  0  0  0  0  0

until b==(b=b_temp)              %loop until no change

```

# Answer
> 4 votes
# Python, ~~203~~ 199 bytes

```
def k(x):
 m,j=max(x),''.join;d=[*map(lambda i:('*'*i).ljust(m),x)];f=sorted(d);print(*d,sep='\n')
 while d!=f:d=[*map(j,zip(*[x.replace('* ',' *')for x in map(j,zip(*d))]))];print('-'*m,*d,sep='\n')

```

# Answer
> 2 votes
# , ~~210~~ 205 bytes

```
l=scan();w=max(l);h=sum(l|1);a=1:h;p=h+1;m=matrix(' ',w,p);m[,p]='+';for(x in a)m[l[x]:1,x]='*';f=function()write(m,'',w,sep='');f();while(any(i<-m[,a]>m[,a+1])){s=which(i);m[,a][s]=' ';m[,a][s+w]='*';f()}

```

Try it online!

reads in the list from stdin; separated by `+` characters instead of `-`. It's a lot longer than I would have thought it would be. Takes advantage of the fact that the comparison `'*'>'+'` evaluates to `FALSE` but `'*'>' '` is `TRUE`, at least on TIO (on my machine I used `'='` which looked a little better).

Managed to golf 5 bytes down from all the techniques I've learned since writing the original answer.

Try it online!

# Answer
> 2 votes
# Japt, ~~69~~ 62 bytes

*-7 bytes thanks to @Shaggy*

```

®ç'x +SpZnUrwÃpQpUrw¹·
V
l o ®V=z d" x""x " z3ÃuW
X¯XbXgJ)Ä ·

```

Learning Japt and wanted to try out a more complicated challenge. Outputs with `x`s and `"`s instead of asterisks and dashes; takes input as an array of numbers. Assumes sorting will be complete within `input.length` steps; correct me if that is ever not the case.

Try it online!

## Explanation

```
                              // implicit: U = input array
 ®   ç'x +SpZnUrwÃ pQpUrw¹ ·  // implicit: V = this line
UmZ{Zç'x +SpZnUrw} pQpUrw) qR // ungolfed
UmZ{             }            // U mapped by the function:
    Zç'x                      //   "x" times this item
         +SpZnUrw             //   plus " " times the max of the input array (Urw) minus this value (Z)
                   pQpUrw)    // push " (Q) times the max
                           qR // join with newlines

V                             // implicit: W = this line

 l o ®   V=z d" x""x " z3Ã uW // implicit: X = this line
Ul o mZ{ZV=z d" x""x " z3} uW // ungolfed
Ul o                          // the array of the range [0, U.length)
     mZ{Z                }    // mapped by the no-arg function:
         V=z                  //   set V to itself rotated 90deg
             d" x""x "        //   replace all " x" with "x " to "fall"
                       z3     // rotate back to normal
                           uW // add  W(the original) to the start

X¯XbXgJ)Ä ·                   // implicit: return this line
Xs0,XbXgJ)+1 qR               // ungolfed
Xs0,                          // get the substring of X from 0 to...
    XbXgJ)+1                  // the first index of the last item, plus one
             qR               // join with newlines

```

# Answer
> 2 votes
# Japt ~~`-R`~~, ~~32~~ ~~31~~ ~~30~~ ~~32~~ ~~31~~ 30 bytes

Really enjoyed this one but not *entirely* happy with the final result, especially after having to add 2 bytes to fix a bug. Still determined to get it down under 30 bytes, though.

Uses `n` instead of `*`.

```
¡P=yÈrSùÍSúÍÃª¡XçnÃ·úÃâ qR² ú-

```

Try it (footer replaces `n`s with `*`s) or run all test cases

```
¡P=yÈrSùÍSúÍÃª¡XçnÃ·úÃâ qR² ú-     :Implicit input of array U
¡                                  :Map
 P=                                :  Reassign to P (initially the empty string)
   y                               :    Transpose P
    È                              :    Pass through the following function and transpose back
     r                             :      Replace
      S                            :        Space
       ù                           :        Left padded with
        Í                          :        "n" to length 2
         SúÍ                       :        With a space right padded with "n" to length 2
            Ã                      :    End function
             ª                     :    Logical OR ('cause it'll still be the empty string on the first iteration)
              ¡                    :      Map each X in U
               Xçn                 :        "n" repeated X times
                  Ã                :      End map
                   ·               :      Join with newlines
                    ú              :      Right pad each with spaces to the length of the longest
                      Ã            :End map
                       â           :Deduplicate
                         q         :Join with
                          R        :  Newline
                           ²       :  Repeated twice
                             ú-    :Right pad each line with "-" to the length of the longest

```

# Answer
> 1 votes
# Haskell, 213 211 208 bytes

```
import Data.List
(?)=replicate
p=transpose
s l|w<-length l,i<-[n?'*'++w?' '|n<-l]=intercalate[w?'-']$i:(p<$>unfoldr f(p i))
f i|i==n=mempty|2>1=Just(n,n)where n=t<$>i
t(a:b:y)|a>b=" *"++t y|2>1=a:t(b:y);t k=k

```

Try it online!

# Answer
> 1 votes
# Javascript, 274 bytes

```
a=>(r="",m=Math.max(...a),b=a.map(n=>Array(m).fill(0).map((_,i)=>i<n)),(k=_=>(b.map(c=>r+=c.map(v=>v?"*":" ").join``.trim()+`
`),r+="-".repeat(m)+`
`,n=0,b.map((r,i)=>(s=b[i+1])&&r.map((c,j)=>s[j]||(n|=s[j]=-(c>0),c>0&&(r[j]=0)))),b=b.map(c=>c.map(n=>n<0?1:n)),n&&k()))(),r)

```

Example code snippet:

```
f =

a=>(r="",m=Math.max(...a),b=a.map(n=>Array(m).fill(0).map((_,i)=>i<n)),(k=_=>(b.map(c=>r+=c.map(v=>v?"*":" ").join``.trim()+`
`),r+="-".repeat(m)+`
`,n=0,b.map((r,i)=>(s=b[i+1])&&r.map((c,j)=>s[j]||(n|=s[j]=-(c>0),c>0&&(r[j]=0)))),b=b.map(c=>c.map(n=>n<0?1:n)),n&&k()))(),r)

o.innerText = f([6,4,2,5,3,1])
```

```
<pre id=o>
```

# Answer
> 1 votes
# , 49 45 bytes

```
' *-'{~2,/@,.~[:((]+[-1|.])]<_1|.!.0])^:a:#&1

```

Try it online!

Takes input as a column vector.

About a third of the bytes are just to conform to the output specs.

* `#&1` Convert to rows of ones, with 0 fill.
* `[:(...)^:a:` Do `...` until a fixed point is reached, keeping track of intermediate results.
* `]<_1|.!.0]` Rotate the rows down, then ask: "where is that less than the original input?" This will pick out just the valid falling pieces, in their "next" position. Call these the "rain".
* `(]+[-1|.])` Add the rain to this step's input minus the rain rotated up. That is, rewind the "rain" one step, remove this rewinded-rain from the input, and then add the not-rewinded rain. This is precisely the rain plus the static pieces, which is what we want for the next iteration.
* `' *-'{~2,/@,.~` Conform to output spec.

---
Tags: code-golf, ascii-art, sorting
---


title: Partial Fractions

text:
# Question
Title: Partial Fractions
Given an input of a string, output the partial fraction in string form.

The partial fraction decomposition of a rational fraction of the form \\$\frac{f(x)}{g(x)}\\$, where \\$f\\$ and \\$g\\$ are polynomials, is its expression as:

$$\frac{f(x)}{g(x)}=p(x)+\sum\_j\frac{f\_j(x)}{g\_j(x)}$$

In this case \\$p\\$ is 0, because we assume that the numerator is smaller than the denominator.

### Input:

In the form of an a list of the coefficients:

```
[[1, 4], [[1,3], [1,3]]]

```

For `(x+4)/(x+3)^2`.

### Output:

In the form of a list too:

```
[[[1], [1, 3]], [[1], [1, 6, 9]]]

```

For `1/(x+3) + 1/(x+3)^2`.

### Assumptions

* The power of - `x^` can be of any power greater than 1
* The fractions are **factorised whenever possible**
* You can output the elements of a list or the list itself
* You can take the input as a list or separate elements
* The numerator highest degree is always lower than the denominator highest degree
* You can take the input and output in any order
* The input will not be in a way such that the numerator and denominator have a factor in common
* You can assume all inputs take this form: $$\frac{something}{(something)(something)(...)}$$
* Note there can be multiple fractions e.g.: $$\frac{x+4}{(x+1)(x-2)(x+3)^2}$$

## Note:

~~This is **not** as easy as it looks~~ This only gets harder. There are multiple cases to follow:

1. Linear factors

$$\frac{N(x)}{(ax+b)(cx+d)}=\frac{A}{ax+b}+\frac{B}{cx+d}$$

2. Repeated linear factors

$$\frac{N(x)}{(ax+b)^2}=\frac{A}{ax+b}+\frac{B}{(ax+b)^2}$$

3. Quadratic factor (non-factorisable)

$$\frac{N(x)}{(ax+b)(x^2+bx+c)}=\frac{A}{ax+b}+\frac{Bx+C}{x^2+bx+c}$$

### Testcases

```
Case 1:
[1,4], [[1,3], [1,2]] -> [[-1], [1,3]], [[2], [1,2]]

```

$$\frac{x+4}{(x+3)(x+2)}=\frac{-1}{x+3}+\frac{2}{x+2}$$

```
Case 2:
[1,4], [[1,3], [1,3]] -> [[1], [1,3]], [[1], [[1,3], [1,3]]]

```

$$\frac{x+4}{(x+3)^2}=\frac{1}{x+3}+\frac{1}{(x+3)^2}$$

```
Case 3:
[2,-1,4], [[1,0], [1,0,4]] -> [[1], [1,0]], [[1,-1], [1,0,4]]

```

$$\frac{2x^2-x+4}{x(x^2+4)}=\frac{1}{x}+\frac{x-1}{x^2+4}$$

# Answer
# Mathematica, 124 bytes

```
#~CoefficientList~x&/@{Numerator@#,Denominator@#}&/@List@@Apart[First@#~FromDigits~x/Fold[Times,(#~FromDigits~x&)/@Last@#]]&

```

View it on Wolfram Cloud!

`Apart` does the heavy lifting here. The rest of the code allows it to work on the specified input and output format.
> 4 votes

# Answer
# Python3, 1029 bytes:

```
import itertools as I
E=enumerate
U=lambda x:{len(x)-i:a for i,a in E(x,1)}
def G(v,r=[]):
 if[]==v:yield r;return
 for k in I.product(*[[-1,0,1]for _ in v[0]]):
  N=[a+b for a,b in zip(v[0],k)]
  if N[0]:yield from G(v[1:],r+[N])
  else:yield from G(v[1:],r+[[-1]+N[1:]])
def P(p):
 if[]==p:return{0:1}
 s=U(p[0])
 for e in p[1:]:
  n={}
  for i,a in E(e,1):
   for A in s:n[A+len(e)-i]=n.get(A+len(e)-i,0)+s[A]*a
  s=n
 return s
T=lambda x:P([eval(i)for j,k in x for i in[j]*k])
H=lambda n,N:[1]+[0]*(max(n)-max(N))
def f(n,d):
 S,D,M={*map(str,d)},[],{}
 for i in S:Y=d.count(eval(i));D+=[(i,Y)]+[(i,1)]*(Y>1 and len(S)==1);M[i]=max(Y,M.get(i,0))
 N=U(n);q,O=[[(a,b,t:=T([(j,M[j])for j in{*M}-{a}]+[(a,M[a]-b)]*(M[a]-b>0)),H(N,t))for a,b in D]],[]
 while q:
  a=q.pop(0)
  O+=[a]
  r={}
  for *_,p,o in a:
   for A,B in P([[*p.values()],o]).items():r[A]=r.get(A,0)+B
  if r==N:return[[i[-1],[eval(i[0])]*int(i[1])]for i in a]
  for i in G([j[-1]for j in a]):
   v=[(A,B,C,z)for (A,B,C,_),z in zip(a,i)]
   if v not in O:q+=[v]

```

Try it online!
> 8 votes

---
Tags: code-golf, math, polynomials
---


title: Fastest Gematria calculator

text:
# Question
Title: Fastest Gematria calculator
Gematria is an ancient Jewish method to determine a numeric value of a letter sequence, using a fixed value for each letter. Gematria is originally applied to Hebrew letters, but for the context of this challenge, we'll use Latin script instead. There are many ways to implement Gematria in Latin script, but let's define it as a close as it can be to the original standard encoding. The numbering goes as such:

A = 1, B = 2, C = 3, D = 4, E = 5, F = 6, G = 7, H = 8, I = 9, J = 10, K = 20, L = 30, M = 40, N = 50, O = 60, P = 70, Q = 80, R = 90, S = 100, T = 200, U = 300, V = 400, W = 500, X = 600, Y = 700, Z = 800.

**Your job is to calculate the Gematria value for each character of a string, sum the result and print it or return it.**

**Rules**

* Lowercase and uppercase letters yield the same value. Anything else equals 0. You can assume the input encoding will always be ASCII.
* You can input the file in whatever method you see fit, be it loading it from a file, piping it in the terminal or baking it into the source code.
* You can use any method you see fit in order to make this go fast, except const evaluation of the input's value and baking *that* into the binary or a similar method. That would be way too easy. The calculation must happen locally on runtime.

And here's a naïve implementation in Rust to provide an example implementation:

```
#![feature(exclusive_range_pattern)]
fn char_to_number(mut letter: char) -> u32 {
    // map to lowercase as casing doesn't matter in Gematria
    letter = letter.to_ascii_lowercase();
    // get numerical value relative to 'a', mod 9 and plus 1 because a = 1, not 0.
    // overflow doesn't matter here because all valid ranges ahead have valid values
    let num_value = ((letter as u32).overflowing_sub('a' as u32).0) % 9 + 1;
    // map according to the Gematria skip rule
    match letter.to_ascii_lowercase() {
        'a'..'j' => num_value, // simply its value: 1, 2, 3...
        'j'..'s' => num_value * 10, // in jumps of 10: 10, 20, 30...
        's'..='z' => num_value * 100, // in jumps of 100: 100, 200, 300...
        _ => 0 // anything else has no value
    }
}

fn gematria(word: &str) -> u64 {
    word
        .chars()
        .map(char_to_number)
        .map(|it| it as u64) // convert to a bigger type before summing
        .sum()
}

```

In order to measure speed, each implementation will be fed the exact same file: a random 100MB text file from Github: https://github.com/awhipp/100mb-daily-random-text/releases/tag/v20221005

The speed of my implementation, measured with Measure-Command, completes in ~573ms and yields the number `9140634224`. I compiled using -O 3 and baked the input text into the source code, and then ran the code on an Intel i5-10400 CPU.

# Answer
> 7 votes
# Rust, ≈ 10 ms

Compile with `cargo build --release`, run with `target/release/gematria random-20221005.txt`.

**`Cargo.toml`**

```
[package]
name = "gematria"
version = "0.1.0"
edition = "2021"

[dependencies]
memmap = "0.7.0"
rayon = "1.5.3"

```

**`src/main.rs`**

```
use core::arch::x86_64::*;
use memmap::MmapOptions;
use rayon::prelude::*;
use std::env::args;
use std::fs::File;
use std::io;

fn gematria(bytes: &[u8]) -> u64 {
    let (prefix, vecs, suffix) = unsafe { bytes.align_to::<__m256i>() };

    let (mut sum0, mut sum10, mut sum19) = vecs
        .par_chunks(2048)
        .map(|chunk| unsafe {
            let splat32 = _mm256_set1_epi8(32);
            let splat123 = _mm256_set1_epi8(123);
            let splat229 = _mm256_set1_epi8(-27);
            let splat0 = _mm256_set1_epi8(0);
            let splat10 = _mm256_set1_epi8(10);
            let splat19 = _mm256_set1_epi8(19);

            let mut sum0 = splat0;
            let mut sum10 = splat0;
            let mut sum19 = splat0;

            for &vec in chunk {
                let x = _mm256_subs_epu8(
                    _mm256_sub_epi8(_mm256_or_si256(vec, splat32), splat123),
                    splat229,
                );
                sum0 = _mm256_add_epi64(sum0, _mm256_sad_epu8(x, splat0));
                sum10 = _mm256_add_epi64(sum10, _mm256_sad_epu8(x, splat10));
                sum19 = _mm256_add_epi64(sum19, _mm256_sad_epu8(x, splat19));
            }

            (
                (_mm256_extract_epi64(sum0, 0)
                    + _mm256_extract_epi64(sum0, 1)
                    + _mm256_extract_epi64(sum0, 2)
                    + _mm256_extract_epi64(sum0, 3)) as u64,
                (_mm256_extract_epi64(sum10, 0)
                    + _mm256_extract_epi64(sum10, 1)
                    + _mm256_extract_epi64(sum10, 2)
                    + _mm256_extract_epi64(sum10, 3)) as u64,
                (_mm256_extract_epi64(sum19, 0)
                    + _mm256_extract_epi64(sum19, 1)
                    + _mm256_extract_epi64(sum19, 2)
                    + _mm256_extract_epi64(sum19, 3)) as u64,
            )
        })
        .reduce(
            || (0, 0, 0),
            |(a0, a10, a19), (b0, b10, b19)| (a0 + b0, a10 + b10, a19 + b19),
        );

    for affix in [prefix, suffix] {
        for &byte in affix {
            let x = (byte | 32).wrapping_sub(123).saturating_sub(229);
            sum0 += x as u64;
            sum10 += x.abs_diff(10) as u64;
            sum19 += x.abs_diff(19) as u64;
        }
    }

    (101 * sum0 + 9 * sum10) / 2 + 45 * sum19 - 900 * bytes.len() as u64
}

fn main() -> io::Result<()> {
    let [_, filename]: [String; 2] = Vec::from_iter(args()).try_into().expect("missing filename");
    let file = File::open(filename)?;
    let mmap = unsafe { MmapOptions::new().map(&file)? };
    println!("{}", gematria(&mmap[..]));
    Ok(())
}

```

# Answer
> 4 votes
# C++ (clang), ~21 ms on my Linux machine

```
#include <array>
#include <chrono>
#include <fcntl.h>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>
#include <unistd.h>

constexpr std::array<unsigned long, 128> numbering {
    // ASCII NUL to @
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    // A to Z
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60,
    70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800,
    // [ \ ] ^ _ `
    0, 0, 0, 0, 0, 0,
    // a to z
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60,
    70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800,
    // all the rest up to 127
    0, 0, 0, 0, 0
};

struct accumulate_block
{
    void operator()(const char* first, const char* last, std::vector<unsigned long>::reference result) {
        result = 0;
        for (const char* str = first; str < last; ++str)
            result += numbering[*str];
    }
};

int main() {
    const auto start = std::chrono::high_resolution_clock::now();

    auto fd = open("random-20221005.txt", O_RDONLY);
    posix_fadvise(fd, 0, 0, 1);

    constexpr std::size_t buffer_size = 4 * 1024 * 1024;
    constexpr unsigned long num_threads = 8;
    constexpr unsigned long min_per_thread = buffer_size / num_threads;
    std::vector<unsigned long> results(num_threads);
    std::vector<std::thread> threads(num_threads - 1);
    char buffer[buffer_size];

    unsigned long count = 0;
    while (const std::size_t bytes_read = read(fd, buffer, buffer_size)) {
        const char* block_start = buffer;
        unsigned long const block_size = bytes_read / num_threads;
        for(unsigned long i = 0; i < num_threads - 1; ++i) {
            const char* block_end = block_start + block_size;
            threads[i] = std::thread(accumulate_block(), block_start, block_end, std::ref(results[i]));
            block_start = block_end;
        }
        accumulate_block()(block_start, buffer + bytes_read, results[num_threads - 1]);
        for(auto& entry: threads) {
            entry.join();
        }
        count = std::accumulate(results.begin() , results.end(), count);
    }

    const auto finish = std::chrono::high_resolution_clock::now();

    constexpr unsigned long expected = 9140634224L;
    const char* checker[] = {"\xE2\x9C\x95", "\xE2\x9C\x93"};
    std::cout << "count = " << count << " " << checker[count == expected] << "\n";

    const auto ms_interval = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start);
    const std::chrono::duration<double, std::milli> ms_double = finish - start;
    std::cout << ms_interval.count() << " ms\n";
    std::cout << ms_double.count() << " ms\n";

    return 0;
}

```

Outputs:

```
count = 9140634224 ✓
21 ms
21.8556 ms

```

Compiled with clang++ \\$14.0.0\\$ using `-O3 -march=native -std=gnu++20`

# Answer
> 0 votes
# Julia 1.0, 140 bytes

```
!x=sum(getindex.((Dict(Char.([1:255...]).=>[zeros(Int,64)...,1:9...,10:10:90...,100:100:800...,zeros(Int,165)...]),),collect(uppercase(x))))

```

Try it online!

# Answer
> 0 votes
# C# (.NET Core 6), ~60 ms on my Windows machine

```
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
var data = File.ReadAllBytes("random-20221005.txt");
sw.Stop();
var readTime = sw.ElapsedMilliseconds;

sw.Restart();
var list = new List<long>();
long taskCount = 16;
long taskSize = data.Length / taskCount;
for (long i = 0; i < taskCount; i++)
    list.Add(i * taskSize);

long grandTotal = 0;
Parallel.ForEach(list, start =>
{
    var lookup = new long[] {
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800,
        0, 0, 0, 0, 0, 0,
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800,
        0, 0, 0, 0, 0
    };
    long total = 0;
    long end = start + taskSize;
    for (long i = start; i < end; i++)
        total += lookup[data[i]];
    grandTotal += total;
});

sw.Stop();
var calcTime = sw.ElapsedMilliseconds;

Console.WriteLine($"read time: {readTime} ms");
Console.WriteLine($"calc time: {calcTime} ms");
Console.WriteLine($"total time: {readTime + calcTime} ms");
Console.WriteLine($"result: {grandTotal}");

```

**Output:**

```
read time: 48 ms
calc time: 12 ms
total time: 60 ms
result: 9140634224

```

**Ouput without parallelization:**

```
read time: 48 ms
calc time: 64 ms
total time: 112 ms
result: 9140634224

```

# Answer
> 0 votes
# Python (multithreaded + numpy + numba) \<30ms total

windows i7-8750H windows laptop, imdisk ramdisk

```
import numpy as np
from numba import jit
import os
from concurrent.futures import ThreadPoolExecutor

@jit(nogil=True, fastmath=True)
def counter(full_dict, bytearr):
    total = 0
    for i in bytearr:
        total += full_dict[i]
    return total
_ = counter(np.zeros((128,), dtype=np.int32), b'abc') #to compile

def final_fast_gematria(filename, chunksize=600000, max_threads=4):
    maindict = {65: 1, 66: 2, 67: 3, 68: 4, 69: 5, 70: 6, 71: 7, 72: 8, 73: 9, 74: 10, \
                75: 20, 76: 30, 77: 40, 78: 50, 79: 60, 80: 70, 81: 80, 82: 90, 83: 100, \
                84: 200, 85: 300, 86: 400, 87: 500, 88: 600, 89: 700, 90: 800}
    full_dict = {**{i:0 for i in range(128)}, **maindict, **{key+32:val for key,val in maindict.items()}}
    full_dict = np.array(tuple(full_dict.values()), dtype=np.int32)
    threads = []
    with ThreadPoolExecutor(max_workers=max_threads) as executor:
        with open(filename, 'rb', 0) as f:
            filesize = os.fstat(f.fileno()).st_size
            for _ in range(filesize//chunksize - 1):
                threads.append(executor.submit(counter, full_dict, f.read(chunksize)))
            return counter(full_dict, f.read()) + sum(thread.result() for thread in threads)

```

---

```
print(final_fast_gematria("E:/random-20221005.txt"))

```

---

```
9140634224

```

---

```
%%timeit -n 2 -r 10
final_fast_gematria("E:/random-20221005.txt")

```

---

```
27.9 ms ± 1.11 ms per loop (mean ± std. dev. of 10 runs, 2 loops each)

```

---

## Read time

```
def only_read(filename, chunksize=600000):
with open(filename, 'rb', chunksize) as f:
    filesize = os.fstat(f.fileno()).st_size
    for _ in range(1 + filesize//chunksize):
        f.read(600000)

```

---

```
%%timeit -n 1 -r 10
only_read("E:/random-20221005.txt")

```

---

```
22.6 ms ± 985 µs per loop (mean ± std. dev. of 10 runs, 1 loop each)

```

notebook with other variants link

---
Tags: number, parsing, fastest-code
---


title: Atbash Self Palindromes

text:
# Question
Title: Atbash Self Palindromes
Consider the Atbash transformation:

```
A|B|C|D|E|F|G|H|I|J|K|L|M
Z|Y|X|W|V|U|T|S|R|Q|P|O|N

```

Where A ⇔ Z and L ⇔ O, e.g. There is an interesting property that some words share. When some strings are translated to their atbash-equivalent, said translation is the original word reversed. I call these *Atbash Self Palindromes*.

As an example, let's translate *WIZARD*:

```
W → D
I → R
Z → A
A → Z
R → I
D → W
```

The result is *DRAZIW*, which is *WIZARD* reversed. Thus, *WIZARD* is an atbash self palindrome.

**Objective** Given a string of printable ASCII characters, output or return a truthy value if that string is an atbash self palindrome, and a falsey value otherwise. (This is done through STDIN, closest equivalent, functional input, etc. If your language cannot do any of these, ~~consider choosing a different language~~ you may hardcode the input.) You should do this case-insensitively. If the input is a palindrome and is unaffected by the atbash seqeunce, you should still output true, since a palindrome + itself is a palindrome. This is a , so the shortest program in bytes wins.

# Test cases

```
"Input" => true, false

"WIZARD" => true
"Wizard" => true // case doesn't matter
"wIzArD" => true
"W I Z A R D" => true
"W IZ ARD" => false // the atbash of this is D RA ZIW, which is not a palindrome of W IZ ARD
"ABCXYZ" => true // ZYXCBA
"345 09%" => false // is not a palindrome
"ev" => true // ve
"AZGDFSSF IJHSDFIU HFIA" => false
"Zyba" => true
"-AZ" => false // -ZA is not a reverse of -AZ
"Tree vvig" => true // Givv eert
"$%%$" => true // palindrome
"A$&$z" => true // z$&$A

```

---

## Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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

```
## Language Name, 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, <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, 43 + 2 (-p flag) = 45 bytes

```

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

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

```

```
var QUESTION_ID=68757,OVERRIDE_USER=44713;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>
```

# Answer
# RX, ~~9~~ 8 bytes

Heavily inspired by Retina, I made this a few days ago. Code:

```
prR`w$rM

```

Explanation:

```
prR`w$rM

p         # Start pattern
 r        # Reversed lowercase alphabet
  R       # Reversed uppercase alphabet
   `      # Next pattern
    w     # Equivalent to a-zA-Z_0-9 (word pattern)
     $    # End pattern and compute regex
      r   # Reverse input
       M  # Change mode to Match mode, compares the atbash string with the reversed string.

```

Try it here!
> 8 votes

# Answer
# Pyth, ~~10~~ 9 bytes

```
qJrz0_XJG

```

Try this fiddle online or verify all test cases at once.

## Explanation

```
qJrz0_XJG
  rz0      Lowercase input
 J         Store a copy in J
     _XJG  Translate J with the reverse alphabet and reverse
q          Compare

```
> 11 votes

# Answer
# Julia, 96 bytes

```
s->join([get(Dict(zip([u=map(Char,65:90);],reverse(u))),c,c)for c=(S=uppercase(s))])==reverse(S)

```

This is a lambda function that accepts a string and returns a string. To call it, assign it to a variable.

Ungolfed:

```
function f(s::AbstractString)
    # Get all of the uppercase letters A-Z
    u = map(Char, 65:90)

    # Create a dictionary for the transformation
    D = Dict(zip(u, reverse(u)))

    # Uppercase the input
    S = uppercase(s)

    return join([get(D, c, c) for c in S]) == reverse(S)
end

```
> 6 votes

# Answer
# GNU Sed, 105

```
s/.*/\l&/
h
y/abcdefghijklmnopqrstuvwxyz/zyxwvutsrqponmlkjihgfedcba/
G
:
s/\(.\)\n\1/\n/
t
/^.$/{c1
q}
c0

```

Outputs 1 for truthy and 0 for falsey.

I tried to do this in Retina, but couldn't figure out how to save the string before Atbash transliteration for reverse comparison with after. Perhaps there is a better way.

Sed's `y` transliteration command leaves a lot to be desired.
> 5 votes

# Answer
# Bash + Linux utils, 56

```
tr a-z `printf %s {z..a}`<<<${1,,}|cmp - <(rev<<<${1,,})

```

Outputs the empty string for Truthy and something like `- /dev/fd/63 differ: byte 1, line 1` for Falsey. If this is not acceptable then we can add `-s` for an extra 3 bytes and use the standard Unix return codes of 0 for Success (Truthy) and 1 for Failure (Falsey).
> 5 votes

# Answer
## Retina, 44 bytes

```
$
¶$_
T`lL`Ro`.+$
+`(¶.*)(.)
$2$1
i`^(.+)\1$

```

Prints `1` or `0`. The byte count assumes that the file is encoded as ISO 8859-1.

Try it online!

This answer was largely inspired by DigitalTrauma's sed answer but then again I guess there aren't that many approaches to this challenge in the first place.

### Explanation

Whenever you see a , the first thing Retina does after splitting the code into lines is to replace all of those pilcrows with linefeeds. This allows the inclusion of linefeeds for a single byte even though linefeeds are Retina's stage separator.

```
$
¶$_

```

We start by duplicating the input. We match the end of the input with `$` and insert a linefeed along with the input itself (using `$_`).

```
T`lL`Ro`.+$

```

A transliteration stage. Let's start with the regex: `.+$`. It matches the second copy of the input (by ensuring the match goes until the end of the string). So only characters in the second copy will be transliterated. The transliteration itself makes use of some very recent features. `l` and `L` are character classes for lower and upper case letters, respectively. `o` refers to the other character set of the transliteration and `R` reverses it. So the two character sets expand to:

```
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba

```

You'll notice that this swaps the case while doing the Atbash cypher, but we'll do the final comparison case-insensitively anyway.

```
+`(¶.*)(.)
$2$1

```

Now we reverse the second copy. Unfortunately, Retina doesn't have a convenient way for doing that yet, so we'll have to move one character from the end to the front at a time. This is done by repurposing the linefeed separator as a marker of which part hasn't been reversed yet. We match that part but capture the last character separately. That character goes in front, and the remainder is unchanged. The `+` tells Retina to do this repeatedly until it's no longer possible (because  is at the end of the string).

```
i`^(.+)\1$

```

Finally, we check whether the two strings are the same. The `i` makes the pattern case-insensitive - conveniently, in .NET, this means that backreferences are also case-insensitive. You might notice that we no longer have a separator between the original input and the modified copy. We don't need one though, because they are the same length, and if the string now consists exactly of the same string twice (up to case), then those must be the original and the modified string. If you're wondering what happened to the trailing linefeed that we used as a marker, it's still there, but in many regex flavours `$` also matches *before* the last character of the string if that character is a linefeed.

Since this stage only consists of a single line, it is taken to be a match stage, which counts the number of matches. If the input is an Atbash palindrome, we'll get exactly one match and the output is `1`. If not, then this regex won't match and the output will be `0`.
> 5 votes

# Answer
# , 15 chars / 30 bytes

```
ïþ)Ī(ᶐ,ᶐᴙ)ᴙ≔ïþ)

```

`Try it here (Firefox only).`

# Explanation

```
ïþ)Ī(ᶐ,ᶐᴙ)ᴙ≔ïþ) // implicit: ï=input, ᶐ=A-Z
ïþ)             // ï.toUpperCase()
   Ī(ᶐ,ᶐᴙ)ᴙ     // transliterate input from A-Z to Z-A, then reverse
           ≔ïþ) // check if that's still equal to ï.toUpperCase()
                // implicit output

```
> 4 votes

# Answer
# Parenthetic, 658 bytes

```
((()()())(()(((()))))((()()((())))))((()()())(()(((())))()()())((())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))((()()())(()(((())))())((()())((()(((())))()()))((()()()())((()(())(()))(()(((())))()())(()((()))))(()((())))((()((()))())((()(())(())())((()(()))(()(((())))()()())((()(()()))((())()()()()()()()()()()()()()()()()()()()()()()()()())((()(()()))((()(()())())((()((()))(()))(()(((())))()())))(()(((())))()()())))))((()(((())))())((()((()))()())(()(((())))()())))))))((()(())(()))((()()()(()))((()()()()())(()(((()))))))((()(((())))())((()()()()())(()(((())))))))

```

Only works for all caps without whitespace right now, using this modified version of the script so that it supports reading from stdin:

```
#!/usr/bin/env python
from collections import defaultdict
from itertools import izip
import copy
import operator
import os
import sys

# map from paren strings to english names
# for the predefined symbols (lambda, etc)
to_english = defaultdict(lambda:None,\
    {'()': 'lambda',
     '()()': 'define',
     '(())': 'plus',
     '(()())': 'minus',
     '()(())': 'mult',
     '(())()': 'div',
     '()()()': 'if',
     '((()))': 'empty',
     '()()()()': 'charsof',
     '()()(())': 'reverse',
     '()(())()': 'LE',
     '()(()())': 'not',
     '(()())()': 'intofchar',
     '()((()))': 'readline',
     '((()))()': 'cons',
     '(())(())': 'equal',
     '((()))(())': 'car',
     '((()))()()': 'cdr',
     '(())(())()': 'char',
     '(())()(())': 'string'})

# map from english to parenthetic
to_scheme = defaultdict(lambda:None)
for k,v in to_english.iteritems():
    to_scheme[v] = k

def Error(errorString = 'unmatched parens', debug_mode = True):
    if debug_mode:
        print "Error: " + errorString
        sys.exit()
    else:
        raise Exception('paren mismatch')

def bracketsMatch(chars):
    """Returns False if any parentheses in `chars` are not matched
    properly. Returns True otherwise.
    """
    level = 0
    for p in chars:
        if p == '(':
            level += 1
        elif p == ')':
            level -= 1
        if level < 0:
            return False
    return level == 0

def get_exprs(chars):
    """Returns a list of character sequences such that for each sequence,
    the first and last parenthesis match.
    For example, "(())()()" would be split into ["(())", "()", "()"]
    """
    level = 0
    current = []
    for p in chars:
        if p == '(' or p == ')':
            current.append(p)
        if p == '(':
            level += 1
        elif p == ')':
            level -= 1
        if level == 0:
            yield current
            current = []

## built-in functions ##
def builtin_accumulate(init, accumulate, environment, params):
    """Helper function that handles common logic for builtin functions.
    Given an initial value, and a two-parameter function, the environment, and
    a list of params to reduce, this function will reduce [init] + params using
    the accumulate function and finally returns the resulting value.
    """
    result = init
    for param in params:
        value = interpret(param, environment)
        try: result = accumulate(result, value)
        except: Error(str(value) + ' is not the correct type')
    return result

def builtin_plus(environment, params):
    if len(params) >= 1:
        return builtin_accumulate(interpret(params[0], environment), operator.add, environment, params[1:])
    else:
        return 0.0

def builtin_minus(environment, params):
    if len(params) == 0:
        Error('subtraction requires at least 1 param')
    return builtin_accumulate(interpret(params[0], environment), operator.sub, environment, params[1:])

def builtin_mult(environment, params):
    return builtin_accumulate(1.0, operator.mul, environment, params)

def builtin_div(environment, params):
    if len(params) == 0:
        Error('division requires at least 1 param')
    return builtin_accumulate(interpret(params[0], environment), operator.div, environment, params[1:])

def builtin_LE(environment, params):
    return interpret(params[0], environment) <= interpret(params[1], environment)

def builtin_lambda(environment, params):
    bodies = [body for body in params[1:]]
    params = params[0][1]
    if len(bodies) == 0:
        Error("a function had no body")
    for kind, name in params:
        if kind != 'symbol':
            Error('lambda must have only symbols as arguments')
    def ret(old_environment, arguments):
        #print bodies
        try:
            # create new environment based on args
            environment = copy.copy(old_environment)
            for param, arg in izip(params, arguments):
                environment[param[1]] = interpret(arg, old_environment)
            # evaluate the function bodies using the new environment
            return interpret_trees(bodies, environment, False)
        except:
            Error("Error evaluating a function")
    return ret

def builtin_equal(environment, params):
    for param1, param2 in izip(params[:-1], params[1:]):
        if interpret(param1, environment) != interpret(param2, environment):
            return False
    return True

def builtin_if(environment, params):
    if len(params) != 3:
        Error("'if' takes in exactly 3 params")
    if interpret(params[0], environment):
        return interpret(params[1], environment)
    return interpret(params[2], environment)

def builtin_not(environment, params):
    return False if interpret(params[0], environment) else True

def builtin_cons(environment, params):
    return (interpret(params[0], environment), interpret(params[1], environment))

def builtin_car(environment, params):
    result = interpret(params[0], environment)
    if not isinstance(result, tuple):
        Error("car must only be called on tuples")
    return result[0]

def builtin_cdr(environment, params):
    result = interpret(params[0], environment)
    if not isinstance(result, tuple):
        Error("cdr must only be called on tuples")
    return result[1]

def builtin_char(environment, params):
    result = interpret(params[0], environment)
    if result != int(result):
        Error("char must only be called on integers")
    return chr(int(result))

def builtin_intofchar(environment, params):
    result = interpret(params[0], environment)
    result = ord(result)
    return result

def builtin_string(environment, params):
    result = ''
    cur = interpret(params[0], environment)
    while cur != ():
        if not isinstance(cur, tuple) or not isinstance(cur[1], tuple):
            Error("string only works on linked lists")
        result += cur[0]
        cur = cur[1]
    return result

def unmakelinked(llist):
    result = ()
    while llist != ():
        if not isinstance(llist, tuple) or not isinstance(llist[1], tuple):
            Error("only works on linked lists")
        result += (llist[0],)
        llist = llist[1]
    return result

def makelinked(tup):
    result = ()
    while tup != ():
        result = (tup[-1],result)
        tup = tup[:-1]
    return result

def builtin_reverse(environment, params):
    result = interpret(params[0], environment)
    result = makelinked(unmakelinked(result)[::-1])
    return result

def builtin_charsof(environment, params):
    result = interpret(params[0], environment)
    result = makelinked(tuple(result))
    return result

def builtin_readline(environment, params):
    result = raw_input()
    return result

# define the default (top-level) scope
default_environment = \
    {to_scheme['plus']: builtin_plus,
     to_scheme['minus']: builtin_minus,
     to_scheme['mult']: builtin_mult,
     to_scheme['div']: builtin_div,
     to_scheme['lambda']: builtin_lambda,
     to_scheme['if']: builtin_if,
     to_scheme['equal']: builtin_equal,
     to_scheme['LE']: builtin_LE,
     to_scheme['not']: builtin_not,
     to_scheme['empty']: (),
     to_scheme['car']: builtin_car,
     to_scheme['cdr']: builtin_cdr,
     to_scheme['cons']: builtin_cons,
     to_scheme['char']: builtin_char,
     to_scheme['string']: builtin_string,
     to_scheme['readline']: builtin_readline,
     to_scheme['charsof']: builtin_charsof,
     to_scheme['reverse']: builtin_reverse,
     to_scheme['intofchar']: builtin_intofchar}

# parse the tokens into an AST
def parse(tokens):
    """Accepts a list of parentheses and returns a list of ASTs.
    Each AST is a pair (type, value).
    If type is 'symbol', value will be the paren sequence corresponding
    to the symbol.
    If type is 'int', value will be a float that is equal to an int.
    If type is expr, value will be a list of ASTs.
    """
    # check for errors
    if not bracketsMatch(tokens):
        Error('paren mismatch')
    # to return - a list of exprs
    exprs = []
    for expr in get_exprs(tokens):
        # check for errors
        if len(expr) < 2:
            Error('too few tokens in: ' + ''.join(expr))
        elif expr[0] != '(' or expr[-1] != ')':
            Error('expression found without () as wrapper')
        # pop off starting and ending ()s
        expr = expr[1:-1]
        # symbol
        if expr[:2] == ['(', ')'] and len(expr) > 2:
            exprs.append(('symbol', ''.join(expr[2:])))
        # integer
        elif expr[:4] == ['(', '(', ')', ')'] and len(expr) >= 4:
            exprs.append(('num', expr[4:].count('(')))
        # expr
        else:
            exprs.append(('expr', parse(expr)))
    return exprs

def interpret(tree, environment):
    """Interpret a single tree (may not be a define) and return the result"""
    kind, value = tree
    if kind == 'num':
        return float(value)
    elif kind == 'symbol':
        if value in environment:
            return environment[value]
        else:
            Error('Unresolved symbol - ' + value)
    elif kind == 'expr':
        function = interpret(value[0], environment)
        if not hasattr(function, '__call__'):
            Error('Symbol "'+value[0]+'" is not a function.')
        return function(environment, value[1:])
    else:
        Error("Unknown tree kind")

def interpret_trees(trees, environment, doprint = True):
    """Interpret a sequence of trees (may contain defines)
    and output the result.
    The trees passed in should be ASTs as returned by parse().
    If doprint is true, the post-interpretation value of each tree is printed.
    """
    environment = copy.copy(environment)
    # hoist define statements (note: trees.sort is stable)
    #trees.sort(key = lambda x: 0 if x[0] == 'expr' and x[1][0][1] == to_scheme['define'] else 1)
    ret = None
    for tree in trees:
        if tree[0] == 'expr' and tree[1][0][0] == 'symbol' and tree[1][0][1] == to_scheme['define']:
            try:
                symbol = tree[1][1]
                if symbol[0] != 'symbol':
                    Error('first argument to define must be a symbol')
                symbol = symbol[1]
                value = tree[1][2]
                environment[symbol] = interpret(value, environment)
            except:
                Error('error evaluating define statement')
        else:
            ret = interpret(tree, environment)
            if doprint:
                print ret,
    return ret

# read in the code ignoring all characters but '(' and ')'
f = open(sys.argv[1],'r')
code = []
for line in f.readlines():
    code += [c for c in line if c in '()']

# parse and interpret the code. print 'Parenthesis Mismatch'
# if an error occured.
#try:
syntax_trees = parse(code)
interpret_trees(syntax_trees, default_environment)
#except:
#    print 'Parenthesis Mismatch'

```

## Explanation

```
(
  define
  (() ()())
  input [[[[]]]]
  (() (((()))))
  exec readline
  ( (() ()((()))) )
)
(
  define
  (() ()())
  value of 'A' [[[[]]]] [][][]
  (() (((())))()()())
  65
  ((()) ()()()()()()()()()()
        ()()()()()()()()()()
        ()()()()()()()()()()
        ()()()()()()()()()()
        ()()()()()()()()()()
        ()()()()()()()()()()
        ()()()()())
)
(
  define
  (() ()())
  atbash [[[[]]]] []
  (() (((())))())
  (
    lambda
    (() ())
    (
      list [[[[]]]] [][]
      (() (((())))()())
    )
    (
      if
      (() ()()())
      (
        equal
        (() (())(()))
        list
        (() (((())))()())
        empty
        (() ((())))
      )
      then return empty
      (() ((())))
      else
      (
        cons
        (() ((()))())
        (
          char
          (() (())(())())
          (
            plus
            (() (()))
            value of 'A' 65
            (() (((())))()()())
            (
              minus
              (() (()()))
              25
              ((()) ()()()()()()()()()()
                    ()()()()()()()()()()
                    ()()()()())
              (
                minus
                (() (()()))
                (
                  intofchar
                  (() (()())())
                  (
                    car
                    (() ((()))(()))
                    list
                    (() (((())))()())
                  )
                )
                value of 'A' 65
                (() (((())))()()())
              )
            )
          )
        )
        (
          atbash
          (() (((())))())
          (
            cdr
            (() ((()))()())
            list
            (() (((())))()())
          )
        )
      )
    )
  )
)

(
  equals
  (() (())(()))
  (
    reverse
    (() ()()(()))
    (
      charsof
      (() ()()()())
      input
      (() (((()))))
    )
  )
  (
    atbash
    (() (((())))())
    (
      charsof
      (() ()()()())
      input
      (() (((()))))
    )
  )
)

```
> 4 votes

# Answer
# Kerf, 73 bytes

Kerf is a proprietary language in the same general family as APL, J and K. It's possible to write cryptic, compact oneliners and avoid the use of explicit loops:

```
{[s]s:_ s;n:?isnull i:s search\<a:char 97+^26;f:(/a)[i];s match/f[n]:s[n]}

```

However, using the spelled-out aliases for commands instead of the shorthand symbols and using meaningful identifiers makes the program much clearer, and fairly easy to follow even if you aren't familiar with Kerf:

```
def atbash_palindrome(str) {
  str:       tolower str
  alpha:     char range(97, 123)
  indices:   str search mapleft alpha
  encoded:   (reverse alpha)[indices]
  notfound:  which isnull indices
  return     str match reverse encoded[notfound]:str[notfound]
}

```

In action:

```
KeRF> p: {[s]s:_ s;n:?isnull i:s search\<a:char 97+^26;f:(/a)[i];s match/f[n]:s[n]};

KeRF> p mapdown ["WIZARD","Wizard","W I Z A R D","ABCXYZ","345 09%","ev","Zyba","$%%$","-AZ"]
  [1, 1, 1, 1, 0, 1, 1, 1, 0]

```

Kerf probably isn't going to win a ton of codegolf competitions, especially against purpose-built languages, but it might be worth tinkering with if you like the idea of APL-family languages but find the syntax too weird. (*Disclaimer: I'm the author of the reference manual for Kerf.*)
> 4 votes

# Answer
## Python 3, ~~90~~ 85 bytes

```
s=input().upper()
print(s[::-1]==''.join(chr([o,155-o][64<o<91])for o in map(ord,s)))

```

We convert the input to uppercase, and then calculate the Atbashed string by subtracting all ordinals from 155 if they're in the uppercase alphabet range.
> 4 votes

# Answer
# Perl 5, 70 bytes

A subroutine:

```
{$"='';reverse(map/[A-Z]/?chr(155-ord):$_,(@_=split'',uc$_[0]))eq"@_"}

```

See it in use:

```
print sub{...}->("W i z a r d")

```
> 3 votes

# Answer
# Prolog, 121 bytes

```
a(W):-upcase_atom(W,X),atom_codes(X,C),b(C,Z),!,reverse(Z,C).
b([A|T],[R|S]):-(A>64,A<91,R is 77-A+78;R=A),(b(T,S);S=[]).

```

This is called with an atom as input, e.g. `a('WIZARD').`.
> 3 votes

# Answer
# JavaScript (ES6), 91

```
x=>(x=[...x.toLowerCase()]).every(c=>((v=parseInt(c,36))>9?(45-v).toString(36):c)==x.pop())

```

**TEST**

```
F=x=>(x=[...x.toLowerCase()]).every(c=>((v=parseInt(c,36))>9?(45-v).toString(36):c)==x.pop())

console.log=x=>O.textContent+=x+'\n'

;[
 ["WIZARD", true]
,["Wizard", true] // case doesn't matter
,["wIzArD", true]
,["W I Z A R D", true]
,["W IZ ARD", false] // the atbash of this is D RA ZIW, which is not a palindrome of W IZ ARD
,["ABCXYZ", true] // ZYXCBA
,["345 09%", false] // is not a palindrome
,["ev", true] // ve
,["AZGDFSSF IJHSDFIU HFIA", false]
,["Zyba", true]
,["-AZ", false] // -ZA is not a reverse of -AZ
,["Tree vvig", true] // Givv eert
,["$%%$", true] // palindrome
,["$%ZA%$", true]
].forEach(t=>{var i=t[0],x=t[1],r=F(i);
              console.log(i+' -> '+r+(x==r?' OK':' Fail (expected:'+x+')'))})
```

```
<pre id=O></pre>
```
> 3 votes

# Answer
# C, ~~101~~ 97 bytes

As the question specified ASCII characters, this doesn't handle any other encodings.

```
f(char*s){char*p=s+strlen(s);while(*s&&!(isalpha(*--p)?*s<64||*s+*p-27&31:*s-*p))++s;return s>p;}

```

## Explanation

```
int f(char*s)
{
    char *p = s + strlen(s);
    while (*s && !(isalpha(*--p) ? *s<64||*s+*p-27&31 : *s-*p))
        ++s;
    return s > p;
}

```

We make a pointer `p` that begins at the end of the string. We then loop, moving both `s` and `p` towards each other `s` reaches the end. This means that every pair of characters will be checked twice, but this saves a couple of bytes compared to stopping as soon as the pointers cross over.

At each iteration, we check whether `*p` is a letter. If so, check that `*s` is in the range of letters (ASCII 64 upward), and that `*p` and `*s` add up to 27 (mod 32). Non-letters over 64 will fail that test, so we don't need to check `isalpha(*s)`.

If `*p` is not a letter, then we simply test whether it is equal to `*s`. In either case, we terminate the loop before `s` and `p` cross over.

If `s` and `p` have crossed, then every pair of letters matched correctly, so we return true; otherwise we return false.

## Test program

Pass the strings to be tested as command-line arguments. This produces correct output for all the test cases. There is no supplied requirement for the empty string; my implementation returns false for that input.

```
#include <stdio.h>

int main(int argc, char **argv)
{
    while (*++argv)
        printf("\"%s\" => %s\n", *argv, f(*argv)?"true":"false");
    return 0;
}

```
> 3 votes

# Answer
# Vyxal, 7 bytes

```
⇩ḂkaḂĿ=

```

Try it Online!

```
⇩       # Lowercase input
 Ḃ      # Duplicate and reverse
     Ŀ  # Transliterate by...
  kaḂ   # lowercase alphabet and backwards lowercase alphabet
      = # is it equal to the original?

```
> 3 votes

# Answer
# MATL, 23 bytes

Uses current release.

```
jkt"@@2Y2m?_219+]h]tP=A

```

### Examples

```
>> matl
 > jkt"@@2Y2m?_219+]h]tP=A
 >
> Tree vvig
1

>> matl
 > jkt"@@2Y2m?_219+]h]tP=A
 >
> W IZ ARD
0

```
> 2 votes

# Answer
# Japt, ~~30~~ 27 bytes

```
U=Uv)w ¥Ur"[a-z]"_c +4^31 d

```

Try it online!

### How it works

This is based largely on my Japt answer on Swap the Alphabet.

```
U=Uv)w ¥Ur"[a-z]"_c +4^31 d
U=Uv)      // Set U to U.toLowerCase().
w ¥        // Reverse it, and check if it is equal to:
Ur"[a-z]"  //  Take the input and replace each letter with:
 _c +4     //   Take its char code and add 4. This results in
           //   the string      "abc...xyz"
           //   becoming        "efg...|}~".
 ^31       //   XOR the result by 31. This flips its last five 5 bits.
           //   We now have     "zyx...cba".
 d         //   Convert back from a char code.
           // Implicit: output last expression

```
> 2 votes

# Answer
## CJam, 18 bytes

```
qeu_'[,65>_W%erW%=

```

Try it online

Works by converting input to uppercase, performing the translation of letters, flips the string, and checks for equality.
> 2 votes

# Answer
# Ruby, 56 bytes

```
->s{s.upcase!;s==s.tr(x=[*?A..?Z]*'',x.reverse).reverse}

```

It's an anonymous function which takes a string and returns `true` or `false`. It's rather clumsy: In order to save some bytes, it uses the destructive variant of `upcase` (with a `!` after it). `upcase!` unfortunately returns `nil` if nothing is changed (like all numeric input), so some bytes are lost trying to deal with that. Still works tho :)
> 2 votes

# Answer
# Python 3.8 (pre-release), 73 bytes / 76 bytes

## Lambda version: (73 bytes)

```
lambda x:(a:=[*map(ord,x.upper())])==[[c,155-c][64<c<91]for c in a][::-1]

```

Try it online!

## Code version: (76 bytes)

```
a=[*map(ord,input().upper())];print(a==[[c,155-c][64<c<91]for c in a][::-1])

```

Try it online!

## How it works:

* `.upper()` Upper all the char of the input
* `a=[*map(ord,input().upper())]` In both program we store in `a` the list containing the ascii value of each character.
* `[... for c in a]` We iterate through this list
* `[c,155-c][64<c<91]` If our ascii value is beetween 64 and 91 (if the char is uppercase) we "flip" it.
* `a==[...][::-1]` We compare our list with the new formed list reversed

## Note:

If we used Python2, we could save 1 byte on the second program because :

* -3 bytes: `map()` returns a list so we don't need the `[*map()]` syntax anymore
* -2 bytes (and a little adjustment): `print` doesn't need parenthesis
* but +4 bytes because we have to use `raw_input()`instead of `input`
> 2 votes

# Answer
# Fig, \\$8\log\_{256}(96)\approx\\$ 6.585 bytes

```
s$Pcacza

```

Try it online!

```
s        # Are the following equal, ignoring case:
         # Implicit input
 $       # Reverse of...
       a # Lowercased (implicit) input
  P      # Transliterated from
   ca    # Alphabet
     cz  # To reversed alphabet

```
> 2 votes

# Answer
## Python, ~~156~~ 112 bytes

```
a=map(chr,range(65,91))
s=raw_input().upper()
print ''.join([dict(zip(a,a[::-1])).get(i,i) for i in s])==s[::-1]

```

Basically, it makes a dictionary of the translation with uppercase letters and the input is capitalized (if everything were lowercase instead, that would add 5 bytes). Then, for each character in the capitalized input, do the translation and append to a list unless the character is not in the alphabet, in which case append the character as is. Join the entire list and compare to the reversed list.

Shout-out to @Artyer for posting almost exactly as I was going to post before me. But I need to confirm, **this is my work and I did this independently**.

Based on the Julia answer by Alex A. Try it here
> 1 votes

# Answer
## Ruby, 79 77 bytes

```
s=$*[0].upcase
exit(s==s.reverse.tr('A-Z','ZYXWVUTSRQPONMLKJIHGFEDCBA'))?0:1

```

Accepts the word to test as a command-line argument. Exits with code 0 (which is truthy to the shell) if the argument is an atbash self palindrome, or with code 1 otherwise.
> 1 votes

# Answer
# 05AB1E, 8 bytes

Code:

```
lDAAR‡RQ

```

Explanation:

```
l         # Lowercase the implicit input
 D        # Duplicate top of the stack
  AAR     # Push the lowercase alphabet (A) and the lowercase alphabet reversed (AR)
     ‡    # Transliterate a -> b
      R   # Reverse this string
       Q  # Compare with the input string

```

Try it online!
> 1 votes

# Answer
# Factor, ~~118~~ 113 bytes

This is an anonymous function.

```
[ >upper dup >array [ 1string 65 90 [a,b] [ 1string ] map dup reverse zip >hashtable at ] map "" join reverse = ]

```

I don't know of a shorter way to generate an associative array of the alphabet :c
> 1 votes

# Answer
# Clojure, 100 bytes

```
(defn x[b](let[a(.toUpperCase b)c(reverse a)](=(map #(char(if(<= 65(int %)90)(- 155(int %))%))a)c)))

```

It should be possible to cut it down to a single anonymous function, cutting around 10 more bytes (of declarations) but I did not find a way yet.
> 1 votes

# Answer
## MATLAB, 61 bytes

Not the shortest solution, but still interesting

```
f=@(a)~any(changem(upper(a),90:-1:65,65:90)-fliplr(upper(a)))

```
> 1 votes

# Answer
# Japt v2.0a0, 13 bytes

Note the unprintable (charcode 155) at the end of the second line.

```
u
ÔøUr\l_cn#

```

Try it
> 1 votes

# Answer
# Factor \+ `spelling`, 60 bytes

```
[ >lower dup ALPHABET dup reverse zip substitute reverse = ]

```

Try it online!

## Explanation:

* `>lower` Convert to lowercase.

**Stack:** (e.g.) `"wizard"`
* `dup` Duplicate.

**Stack:** `"wizard" "wizard"`
* `ALPHABET` Place the lowercase alphabet on the stack.

**Stack:** `"wizard" "wizard" "abcdefghijklmnopqrstuvwxyz"`
* `dup` Duplicate.

**Stack:** `"wizard" "wizard" "abcdefghijklmnopqrstuvwxyz" "abcdefghijklmnopqrstuvwxyz"`
* `reverse` Reverse.

**Stack:** `"wizard" "wizard" "abcdefghijklmnopqrstuvwxyz" "zyxwvutsrqponmlkjihgfedcba"`
* `zip` Make an associative array from two sequences.

**Stack:** `"wizard" "wizard" { { 97 122 } { 98 121 } { 99 120 } { 100 119 } { 101 118 } { 102 117 } { 103 116 } { 104 115 } { 105 114 } { 106 113 } { 107 112 } { 108 111 } { 109 110 } { 110 109 } { 111 108 } { 112 107 } { 113 106 } { 114 105 } { 115 104 } { 116 103 } { 117 102 } { 118 101 } { 119 100 } { 120 99 } { 121 98 } { 122 97 } }`
* `substitute` Substitute elements in a sequence that have keys in an assoc with their values.

**Stack:** `"wizard" "draziw"`
* `reverse` Reverse.

**Stack:** `"wizard" "wizard"`
* `=` Are they equal?

**Stack:** `t`
> 1 votes

---
Tags: code-golf, string, cryptography, palindrome
---


title: Best partitioning set

text:
# Question
Title: Best partitioning set
Given an array of \\$n\\$ positive integers we will say its *self-sum order* is the number of ways to add elements from it to make \\$n\\$. We will count ways as distinct up to associativity. So \\$1+(2+3)\\$ and \\$(1+2)+3\\$ are not counted as separate ways to make 6, but \\$2+4\\$ and \\$4+2\\$ are counted as separate. Two sums are the same if they are the same when written without parentheses.

You may not reuse elements of the array in your sum, but the same number can appear multiple times in the array. So if the array is `[1,1,2,3]`, then \\$1+1+2\\$ should be counted, but \\$2+2\\$ should not.

As an example here's one array with all the distinct sums listed out:

```
[1,1,2,3]
1+3
3+1
1+1+2
1+2+1
2+1+1

```

It's self sum order is 5.

## Task

Given a non-negative integer, \\$n\\$, as input, output the array of length \\$n\\$ with the highest self-sum order. Since there will be multiple arrays (often just permutations of the same array) with the highest self-sum order, you may output any one of them.

Your answer will be scored by it's big \\$O\\$ asymptotic time complexity in terms of \\$n\\$, with faster algorithms being better.

## Example outputs:

You do not need to output the order it is included for your convenience.

```
0  -> 1    []
1  -> 1    [1]
2  -> 1    [1,1]
3  -> 3    [1,2,3]
4  -> 5    [1,1,2,3]
5  -> 9    [1,1,1,2,3]
6  -> 17   [1,1,2,2,3,4]
7  -> 37   [1,1,1,2,2,3,4]
8  -> 73   [1,1,1,1,2,2,3,4]
9  -> 138  [1,1,1,1,2,2,3,4,5]
10 -> 279  [1,1,1,1,2,2,2,3,4,5]
11 -> 578  [1,1,1,1,2,2,2,3,3,4,5]
12 -> 1228 [1,1,1,1,1,2,2,2,3,3,4,5]
13 -> 2475 [1,1,1,1,1,1,2,2,2,3,3,4,5]
14 -> 4970 [1,1,1,1,1,1,2,2,2,3,3,4,5,6]

```

*These cases were generated by a computer program, there is a chance there is an error. If you believe that there is an error, just let me know.*

# Answer
> 2 votes
# Python3, seems like it might be `o(3^n)` or thereabouts

Tracks subsets and then counts the distinct permutations in closed form, merges together subsets with the same length, sum, and lowest run, and uses a bound to cut off unpromising states (it could be tighter).

```
import collections
import copy
import functools
import random
from fractions import Fraction
from math import factorial

class Subset:
    def __init__(self, n):
        self.high_size = Fraction(1, 1)
        self.high_count = 0
        self.n = n
        self.n_count = 0
        self.sum = 0
    def increment(self):
        self.sum += self.n
        self.n_count += 1
    def restrict(self, x):
        if x >= self.n:
            return
        self.high_size *= Fraction(1, factorial(self.n_count))
        self.high_count += self.n_count
        self.n = x
        self.n_count = 0
    def count_size(self):
        return factorial(self.n_count + self.high_count) * self.high_size * Fraction(1, factorial(self.n_count))
    def state_tuple(self):
        return (self.high_size, self.high_count, self.n, self.n_count, self.sum)
    def __eq__(self, other):
        return self.state_tuple() == other.state_tuple()
    def __hash__(self):
        return hash(self.state_tuple())

@functools.lru_cache(None)
def sum_partitions(k, n, l):
    if n == 0:
        return 1
    if l == 0:
        return 0
    t = 0
    for i in range(1, k + 1):
        if l * i >= n:
            t += sum_partitions(i, n - i, l - 1)
    return t

@functools.lru_cache(None)
def f(partial_sums, k, n, l):
    global best
    if l == 0:
        s = sum(u.count_size() for u in partial_sums)
        best = max(s, best)
        return s
    bound = sum(factorial(u.n_count + u.high_count + l) * u.high_size * sum_partitions(u.n, n - u.sum, l) * Fraction(1, factorial(u.n_count)) for u in partial_sums)
    if bound <= best:
        return 0
    c = 0
    for i in range(1, k + 1):
        a = [copy.deepcopy(u) for u in partial_sums if u.n >= i and u.sum + i <= n and u.sum + l * i >= n]
        b = [copy.deepcopy(u) for u in partial_sums if u.sum + (l - 1) * (i - 1) >= n]
        for u in a:
            u.restrict(i)
            u.increment()
        for u in b:
            u.restrict(i - 1)
        s = a + b
        q = collections.defaultdict(lambda: 0)
        for u in s:
            w = u.high_size
            u.high_size = 0
            q[u] += w
        s = set()
        for u, w in q.items():
            u.high_size = w
            s.add(u)
        c = max(c, f(frozenset(s), i, n, l - 1))
    return c

for n in range(20):
    best = 0
    print(n, f(frozenset([Subset(n)]), n, n, n))

```

---
Tags: fastest-algorithm, integer-partitions
---


title: Palindrome Hello, World

text:
# Question
Title: Palindrome Hello, World
Your task is to create a program that prints "Greetings, Planet!" exactly to the console. Seems simple enough, right? Well, here's the trick. The code must be a palindrome, meaning it reads from right to left the same as in left to right. Standard loopholes are ***NOT*** allowed.

# Answer
> 34 votes
# ///, 37 bytes

```
Greetings, Planet!/!tenalP ,sgniteerG

```

# Answer
> 16 votes
# TI-BASIC, 67 bytes

```
"!tenalP ,sgniteerG"
"Greetings, Planet!"

```

This works because the last line of a program is displayed on the screen, while the first string is essentially treated as a comment.

Each lowercase letter is stored as 2 bytes, and the remaining characters are 1 byte. If I were to bend the rules and print in all caps, it would be **41 bytes**:

```
"!TENALP ,SGNITEERG"
"GREETINGS, PLANET!"

```

# Answer
> 13 votes
I know this is a bit late (and a bit finicky), but...

## \>\<\> (Fish), ~~47~~ ~~45~~ 47 Bytes (really ~~43~~ 45, if I wasn't using the randomized direction)

```
x"!tenalP ,sgniteerG"!|o|!"Greetings, Planet!"x

```

These answers are a bit different to every other; there is a chance for *either direction of code* to be executed.

So, by "printing to console", I assumed you meant printing to stdout. This throws an error; the error is thrown to stderr AFTER the string is printed to stdout.

To prove that this worked both ways, I used the "random direction" director, "x". Fish is a two-dimensional language, so, no matter which way the director points, the code will still (eventually) be executed.

Assuming that the first director points to the right, the characters are loaded to the "stack" in reverse order, then the reverse of the reverse (or the normal text) is printed.

Assuming that both directors point to the left, the characters are, once again, loaded to the "stack" in reverse order (because the code loads it in backwards here, direction is to the left), then the reverse of the reverse (or the normal text) is printed.

If the randomized director points up or down, this won't matter - fish knows to loop to the underside or overside of the code, pointing back to the randomizer. In this way, it will continue to loop with the randomizers until it points inward, towards the code to execute.

The `!|o|!` bit does the following, from both sides:

* `!` skips the next instruction (will always skip `|`)
* `|` is a reflector; it points inward back towards `o`.
* `o` outputs the current item of the stack to console as a character and removes it from the stack.

So, essentially, this is the "two mirrors in a bathroom pressed up together" trick, where I output until I can't anymore.

~~Now using a cat emoji. `>o<` redirects the output inward infinitely, still throwing the error, but I can get away with not using a skip into reflection.~~

Turns out I was right the first time - the second attempt was not *palindromic*, but it was *reflective*.

## Fish (without printing to stderr), 64 Bytes (ew)

```
x"!tenalP ,sgniteerG"!;oooooooooooooooooo;!"Greetings, Planet!"x

```

This dude's a little longer.

It has the same randomized arrow function (to prove it works both ways) and does not print to stderr.

The difference here is obvious; I literally print out every item in the stack, then end execution with `;`.

The `!;` does not end execution immediately, as `!` skips the next item (end exec, in this case) and continues until it hits the other side, which acts as `;!`, wherein it ends execution before it skips anything.

It follows the same randomized direction pattern as the shorter answer.

# Answer
> 11 votes
# Bubblegum, 38 bytes

```
0000000: 73 2f 4a 4d 2d c9 cc 4b 2f d6 51 08 c8 49 cc 4b 2d 51 04  s/JM-..K/.Q..I.K-Q.
0000013: 04 51 2d 4b cc 49 c8 08 51 d6 2f 4b cc c9 2d 4d 4a 2f 73  .Q-K.I..Q./K..-MJ/s

```

# Answer
> 10 votes
## Macaroni 0.0.2, 52 bytes

```
print "Greetings, Planet!""!tenalP ,sgniteerG" tnirp

```

A solution that doesn't use comments. (Mostly because Macaroni doesn't have comments...)

# Answer
> 8 votes
# CJam, 41 bytes

Thanks to Dennis for the three bytes off.

```
"!tenalP ,sgniteerG";"Greetings, Planet!"

```

# Answer
> 7 votes
# Foo, 39 bytes

```
"Greetings, Planet!"!tenalP ,sgniteerG"

```

Try it online.

# Answer
> 6 votes
# JavaScript, 56 bytes

This can run in any browser.

```
alert("Greetings, Planet!")//)"!tenalP ,sgniteerG"(trela

```

# Answer
> 6 votes
# C++, 129 bytes

Trying to do this without comments led me into a deep, dark preprocessor nightmare with no way out that I could see. Instead I've just aimed to get it as short as possible.

```
/**/
#include<cstdio>
int main(){puts("Greetings Planet!");}//*/
/*//};)"!tenalP sgniteerG"(stup{)(niam tni
>oidtsc<edulcni#
/**/

```

# Answer
> 6 votes
# Jelly

**25 bytes**

```
»1ị“RsẈḄ,#ʠU“Uʠ#,ḄẈsR“ị1»

```

Look 'ma, no comments! Try it online!

### How it works

```
»1ị“RsẈḄ,#ʠU“Uʠ#,ḄẈsR“ị1»  Main link. No arguments.

   “        “        “  »  Decompress all three strings; yield a list of strings.
    RsẈḄ,#ʠU               (decompresses to 'Greetings, Planet!')
             Uʠ#,ḄẈsR      (decompresses to ' WafdkmC Posited,')
                      ị1   (decompresses to 'Taarhus')

»1                         Take the maximum of the default argument (0) and 1.
  ị                        Select the string at the index to the left.

```

# Answer
> 5 votes
# GolfScript, 41 bytes

```
"Greetings, Planet!":"!tenalP ,sgniteerG"

```

Look ma, no no-ops! Try it online in Web GolfScript.

The second half of the source code stores the string in the second string.

```
"Greetings, Planet!":"!tenalP ,sgniteerG"
"!tenalP ,sgniteerG"

```

would print

```
Greetings, Planet!Greetings, Planet!

```

# Answer
> 5 votes
## Python 3, 57 bytes

```
print('Greetings, Planet!')#)'!tenalP ,sgniteerG'(tnirp

```

I fixed the issue with parenthesis.

## Python 2, 53 bytes

```
print'Greetings, Planet!'#'!tenalP ,sgniteerG'tnirp

```

I used advantage of the lack of required parenthesis and spaces in Python 2, but there wasn't that big of a difference.

# Answer
> 4 votes
# Stuck, 41 Bytes

```
"Greetings, Planet!"p"!tenalP ,sgniteerG"

```

Fairly similar to the CJam answer, except in Stuck if a print command is issued, automatic stack printing is suppressed.

# Answer
> 4 votes
# 05AB1E, 16 bytes

Code:

```
”!º¥,ÁÙ””ÙÁ,¥º!”

```

Explanation:

```
”!º¥,ÁÙ”          # Compressed string which results in "! Crm, Everywhere".
        ”ÙÁ,¥º!”  # Compressed string which results in "Greetings, Planet!".
                  # Top of stack is implicitly outputted.

```

Try it online!

# Answer
> 3 votes
## Mathematica, 52 bytes

```
Print@"Greetings, Planet!""!tenalP ,sgniteerG"@tnirP

```

Also generates a `Null "!tenalP ,sgniteerG"[tnirP]` which doesn't get printed.

# Answer
> 3 votes
## Fission, ~~45~~ 43 bytes

*Thanks to jimmy23013 for saving 2 bytes.*

```
;"!tenalP ,sgniteerG"R"Greetings, Planet!";

```

Try it online!

`R` initialises an atom which moves to the right. `"` toggles string mode which simply prints the desired string to STDOUT before hitting `;`, which destroys the atom and terminates the program. The first half is simply never executed.

# Answer
> 2 votes
## STATA, 52 bytes

`di "Greetings, Planet!"//"!tenalP ,sgniteerG" id`

A slightly longer (53 byte) version that doesn't use comments is:

```
#d
di "Greetings, Planet!";"!tenalP ,sgniteerG" id
d#

```

`#d [something]` changes the delimiter (initially a carriage return) to `;` unless \[something\] is `cr`, so the first command changes the delimiter to `;`, the second prints the string, and the third (which continues until the end) is apparently a nop, though I have no idea why. I would have guessed that this would throw an error (unrecognized command "!tenalP ,sgniteerG" or something), but apparently not.

# Answer
> 2 votes
# Japt, 29 bytes

This programming language was made after the question was posted, but was not made for this question.

```
`!t?ÓP ,?Ä>ÎG`;`GÎ>Ä?, PÓ?t!`

```

Try it online!

Each `?` is an unprintable Unicode char: U+0082, U+000F, U+000F, and U+0082, respectively.

Fun fact: If Japt had been published a month sooner, it would have legitimately won this challenge.

# Answer
> 2 votes
## APL, 41 bytes

```
'Greetings, Planet!'⍝'!tenalP ,sgniteerG'

```

In APL, the last value is printed and the lamp character (⍝) start a comment.

# Answer
> 2 votes
## GolfScript, 41 bytes

```
"Greetings, Planet!"#"!tenalP ,sgniteerG"

```

Try it online !

# Answer
> 2 votes
# TCL, 80 Bytes

```
proc unknown args {puts "Hello World!"}
}"!dlroW olleH" stup{ sgra nwonknu corp

```

explanation: TCL executes a global proc `unknown` when it encounters a call to an undefined command, the first line redefines that proc to a simple "hello world" program.

TCL's quoting rules are quite subtle, an open brace starts a quoted word that extends to the next *matching* close brace, allowing nested, quoted words. Braces are otherwise treated as normal characters. five words: `}"!dlroW olleH"`, `stup{`, `sgra`, `nwonknu` and `corp`. No command named `}"!dlroW olleH"` has been defined, so the `undefined` proc from the first line is invoked instead.

A similar question was posted on the StackOverflow of antiquity; which has since been closed and deleted. I used my solution as a tongue in cheek TCL sample in this answer, and am now getting comments asking for an explanation, so I recreate my answer here.

# Answer
> 2 votes
## Keg, 41 bytes

```
Greetings\, Planet\!#!\tenalP ,\sgniteerG

```

Try it online!

# Answer
> 1 votes
# Ruby, 43 bytes

```
p"Greetings, Planet!"#"!tenalP ,sgniteerG"p

```

# Answer
> 1 votes
# Lua, 52 Bytes

```
print"Greetings, Planet!"--"!tenalP ,sgniteerG"tnirp

```

In Lua terminal, it is only 44 bytes with

```
="Greetings, Planet!"--"!tenalP ,sgniteerG"=

```

# Answer
> 1 votes
# Vitsy, 41 Bytes

This programming language was made after the question was posted, but was not made for this question.

```
"!tenalP ,sgniteerG"Z"Greetings, Planet!"
```

The `Z` character outputs everything in the stack to STDOUT.

Try it online!

# Answer
> 1 votes
# Unefunge 98 - 49 bytes

```
"!tenalP ,sgniteerG<DC1>"k,@,k"<DC1>Greetings, Planet!"

```

The code above contains two unprintable characters with code 17 (device control 1) represented by `<DC1>`.

# Answer
> 1 votes
## MSM, 73 bytes

```
GGreetings, Planet!.................,.................!tenalP ,sgniteerGG

```

The first half just before the middle `,` builds a reverse greeting string including the additional `G` on the very right. The middle `,` drops it and the rest is a canonical "Hello/Greeting/whatever" program. The additional characters on both ends are needed, because the message contains a `,`. The left one is executed and drops the `s`. Both `,` and `s` need a replacement for the left concatenation dots, hence the `G`s. The `,` on the right isn't executed, but build into the final string.

# Answer
> 1 votes
## Bash, 52 48 bytes

```
echo Greetings, Planet!||!tenalP ,sgniteerG ohce

```

Also works in ksh, zsh, yash, dash. But not tcsh.

```
$ cat x.sh
echo Greetings, Planet!||!tenalP ,sgniteerG ohce
$ bash x.sh
Greetings, Planet!
$ ksh x.sh
Greetings, Planet!
$ zsh x.sh
Greetings, Planet!
$ yash x.sh
Greetings, Planet!
$ dash x.sh
Greetings, Planet!
$ tcsh x.sh
tenalP: Event not found.
$

```

# Answer
> 1 votes
## CoffeeScript, 53 bytes

Similar to Ruby and Lua and pretty much all the variants here.

```
alert 'Greetings, Planet!'#'!tenalP ,sgniteerG' trela

```

# Answer
> 1 votes
# Milky Way 1.5.10, ~~43~~ ~~41~~ 39 bytes

```
"Greetings, Planet!"!tenalP ,sgniteerG"

```

---

### Explanation

```
"Greetings, Planet!"                       # push the string to the stack
                    !                      # output the TOS
                     tenalP ,sgniteerG"    # throws an error and exits

```

---

### Usage

```
python3 milkyway.py <path-to-code>

```

# Answer
> 1 votes
# jq, 44 characters

(42 charactes code + 2 character command line option.)

```
"Greetings, Planet!"//"!tenalP ,sgniteerG"

```

(Not a big deal, posted just for the sake of that operator. Yes, `//` is not comment, is the alternative operator: if its left operand is `null` or `false`, the right operand is returned, otherwise the left operand.)

Sample run:

```
bash-4.3$ jq -nr '"Greetings, Planet!"//"!tenalP ,sgniteerG"'
Greetings, Planet!

```

On-line test (Passing `-r` through URL is not supported – check Raw Output yourself.)

# Answer
> 1 votes
# Emacs Lisp, 60 bytes

```
(message"Greetings, planet!");)"!tenalp , sgniteerG"egassem(

```

As you might have already guessed `;` denotes a comment.

# Answer
> 1 votes
# Fishing, Dock length 41

```
v+CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
  `Greetings, Planet!`P`!tenalp ,sgniteerG`

```

For a palindrome that also includes the dock and is measured in total bytes, this has 132 bytes.

```
v+CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
  `Greetings, Planet!`P`!tenalp ,sgniteerG`  CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC+v

```

---

Fishing prints the stack with `P`. Because the dock ends at the end of the first line, no other fish are caught or executed.

# Answer
> 1 votes
# Golfscript, 41 bytes

`"!tenalP ,sgniteerG";"Greetings, Planet!"`

Pushes `"!tenalP ,sgniteerG"` to stack, removes top of stack (`;`), and pushes `"Greetings, Planet!"`. Stack is printed at end of execution in GolfScript.

# Answer
> 1 votes
# Self-Modifying Brainf\*ck, 67 bytes

```
+[<[<]<[.<]-][0Greetings, Planet!0!tenalP ,sgniteerG0][-[>.]>[>]>]+

```

Where the 0's denote null characters.

The first `<[<]` moves the pointer to the beginning of the message (the last null character) And the following `<[,<]` reads and outputs the message until the terminating null character. This is a pretty long answer, so it probably won't stand a chance, but hey, it's pretty cool.

# Answer
> 1 votes
# Fuzzy Octo Guacamole, 52 bytes

```
'Greetings, Planet!'X@X'!tenalP ,sgniteerG'

```

Pushes `"Greetings, Planet!"` to the stack, pop, print, and end. (`''` pushes the string, `_;` pops and prints, and `@` terminates immediately.

Without the `@`, it would then print `0` after the string.

# Answer
> 1 votes
# C, 72 bytes

```
main(){puts("Greetings, Planet!");}//};)"!tenalP ,sgniteerG"(stup{)(niam

```

# Answer
> 1 votes
## Self-modifying Brainfuck, 47 bytes

```
Greetings, Planet!<[.<]<.[<!tenalP ,sgniteerG

```

The code contains two null-bytes, shown here as `0`:

```
Greetings, Planet0!<[.<]<.[<!0tenalP ,sgniteerG

```

Try it online!

### Explanation

Like the other SMBF answers, this includes the required string in the source code, along with a null-byte as an end-of-string marker. Note that SMBF is like regular BF, except that the source is copied to the front of the tape and the tape head starts at the cell just after the source code.

We can save some bytes over the other answers by putting the actual string at the end, so that we don't have to skip past the actual source code. Finally, we can save one more byte by putting the `!` on the other side of the null-byte which conveniently lets us reuse the `<.` in the mirror image to print the last character (otherwise we'd have to double the `]` to avoid that `<.` is executed). Here is the code:

```
,     Read a character, which is a no-op with no input.
<     Move tape head onto the 'G'.
[.<]  In a loop, print character, move tape head left. This prints the desired
      string except for the '!'. The loop terminates when the tape head reaches
      the null byte.
<     Move the tape head left another cell onto the '!'.
.     Print it.
[     Unmatched square bracket, terminates the program.

```

# Answer
> 1 votes
## Hoon, 41 bytes

```
"Greetings, Planet!":"!tenalP ,sgniteerG"

```

In Hoon, `a:b` means "compute a in the context of b". To include a library, for example, you stick a rune that evaluates the rest of your program in the context of the core containing the library. This is possible because cores also contain the entire kernel and stdlib, so you can nest them and still compute.

Because a string literal is just a constant expression that doesn't depend on the context it is being evaluated in at all, we can replace the entire stdlib with just another constant expression and it will evaluate to the same thing.

# Answer
> 1 votes
# Brachylog, 41 bytes

```
"Greetings, Planet!"w"!tenalP ,sgniteerG"

```

This will call `w - write` with `"Greetings, Planet!"` as input and `"!tenalP ,sgniteerG"` as output. `w` writes its input to `STDOUT` and does nothing with its output.

# Answer
> 1 votes
# Pyth, 41 bytes

```
"Greetings, Planet!"K"!tenalP ,sgniteerG"

```

Prints "Greetings, Planet!", then assigns "!tenalP ,sgniteerG" to K

# Answer
> 1 votes
# PowerShell, 41 bytes

```
"Greetings, Planet!"#"!tenalP ,sgniteerG"

```

Output is implied is PowerShell and anything after `#` is a comment.

# Answer
> 1 votes
# R, 51 bytes

```
cat("Greetings, Planet!")#("!tenalP ,sgniteerG")tac

```

No really original, `#` indicates a commentary in **R**

# Answer
> 1 votes
# Hy, 58 bytes

```
(print "Greetings, Planet!");;("!tenalP ,sgniteerG" tnirp)

```

I'm not competing.

# Answer
> 1 votes
# Vyxal, ~~41~~ ~~19~~ 18 bytes

```
`!±∵ ,∴İ``İ∴, ∵±!`

```

Try it Online!

We can achieve this via string compression. By entering

```
`Greetings, Planet!`øD

```

We get:

```
`İ∴, ∵±!`

```

We therefore just reverse it to get:

```
`!±∵ ,∴İ`

```

The reason why I had to enter `!±∵ ,∴İ` is to fulfill the palindrome requirement.

Vyxal prints the last string outputted to stack, in this case ignoring the first one.

# Answer
> 0 votes
# Dyalog APL, 43 bytes

```
'!tenalP ,sgniteerG'∘⊢∘'Greetings, Planet!'

```

or

```
'Greetings, Planet!'∘⊣∘'!tenalP ,sgniteerG'

```

# Answer
> 0 votes
# Mouse-2002, 47 bytes

```
"Greetings, Planet"33!'$'!33"tenalP ,sgniteerG"

```

I hate that I have to print `!`'s charcode because using it in a string just prints `\n`.

```
things_to_fix_in_my_mouse_reboot.append("EXCLAMATION POINTS ARE THEMSELVES, NOT NEWLINES.")

```

# Answer
> 0 votes
# PlatyPar, 40 bytes

```
"!tenalp ,sgniteerG""Greetings, planet!"

```

Pushes the two strings to the stack. At the end of the program, the **last** item of the stack is printed, so the first inverted one is ignored. I see a lot of other answers like this, except mine doesn't have something between the two strings.

Try it online!

# Answer
> 0 votes
# Microscript, 43 bytes

```
"!tenalP ,sgniteerG"aha"Greetings, Planet!"

```

---

# Microscript II, 40 bytes

Noncompeting, language postdates the question.

```
"!tenalP ,sgniteerG""Greetings, Planet!"

```

# Answer
> 0 votes
# Pylongolf, 43 bytes

```
."Greetings, Planet!"~"!tenalP ,sgniteerG".

```

`~` prints the stack nicely, `.` resets the stack.
`"Greetings, Planet!"` pushes the sentence into the stack, `~` prints it.
The rest is a blur.

EDIT: I saved 2 bytes by removing the `~` symbols on both sides.

# Answer
> 0 votes
# Java, 170 164 bytes

```
interface e{static void main(String[]s){System.out.print("Greetings, Planet!");}}//}};)"!tenalP ,sgniteerG"(trinp.tuo.metsyS{)s][gnirtS(niam diov citats{e ecafretni

```

# Answer
> 0 votes
# Haystack, 43 bytes

```
"Greetings, Planet!"o|o"!tenalP, sgniteerG"

```

Here's how this two-dimensional program works:

* `"Greetings, Planet!"` pushes a string whose content is `Greetings, Planet!` to the stack.
* `o` prints everything in the stack.
* `|` is the needle. The program ends because it found the needle in the haystack!
* `o"!tenalP, sgniteerG"` isn't executed as the needle is found before reaching there.

Hello World example(s) from shebang

# Answer
> 0 votes
## INXW63CTMNZGS4DU, 42 bytes

```
"Greetings, Planet!"#"!tenalP, sgniteerG"

```

A trailing newline is needed at the end

The # character start a comment, and the last value is printed, so this program print "Greetings, Planet!"

# Answer
> 0 votes
# PHP, ~~48~~ 52 bytes

```
echo"Greetings, Planet!";//;"!tenalP ,sgniteerG"ohce

```

`//` comments out the rest of the line, leaving `echo"Greetings, Planet!";`.
No space is needed between `echo` and `"`, meaning this is this the shortest possible response for PHP.

Would have loved a clever excuse to use `/*` `*/`, but couldn't think of one.

# Answer
> 0 votes
# Nim, 49 bytes

```
echo"Greetings, Planet!"#"!tenalP ,sgniteerG"ohce

```

Pretty self-explanatory. Uses Nim's short `echo` syntax and a comment to create the palindrome.

# Answer
> 0 votes
## Straw, 41 bytes

```
(Greetings, Planet!)>)!tenalP ,sgniteerG(

```

Try it online

`(Greetings, Planet!)` push a string on the stack, `>` print it. The rest of the program simply fill the stack with junk.

# Answer
> 0 votes
## AWK, 66 bytes

```
BEGIN{print"Greetings, Planet!"#"!tenalP, sgniteerG"tnirp{NIGEB

```

Could save some bytes if input were allowed, but I assume it isn't.

The input required code would save 15 bytes and be run like this:

```
awk '{$0="Greetings, Planet!"}1#1{"!tenalP, sgniteerG"{' <<< "arbitrary string here"

```

# Answer
> 0 votes
# q/kdb+ 41 bytes

**Solution:**

```
"!tenalP ,sgniteerG";"Greetings, Planet!"

```

**Example:**

```
q)"!tenalP ,sgniteerG";"Greetings, Planet!"
"Greetings, Planet!"

```

**Explanation:**

This is really just two statements separated by a semicolon, `"!tenalP ,sgniteerG"` and `"Greetings, Planet!"`, due to the `;`, the first statement does not get printed to the console.

# Answer
> 0 votes
# Underload, 48 bytes

```
)(Greetings, Planet!)S())(S)!tenalP ,sgniteerG()

```

Uses the fact that non-matching closing brackets don't error on the interpreter that TIO uses.

# How it works

```
) Used to make a matching pair of brackets at the end, so it doesn't error
(Greetings, Planet!)S   Outputs 'Greetings, Planet!'
()   Used to make it so the output command doesn't run a second time, since it gets enclosed in bracket. Also, adds an element to the stack so the 'a' in the '!tenalP, sgniteerG', doesn't error, since 'a' is a command in Underload
)(S)   Pushes S to the stack
!tenalP ,sgniteerG   Reversed 'Greetings, Planet'. Every character is a no-op apart from 'a'
()   Matching pair of brackets I mentioned on the first line

```

Try it Online!

# Answer
> 0 votes
# Java, 192 Bytes

```
public class C{public static void main(String[] args){System.out.print("Greetings, Planet!");}}//}};)"!tenalP ,sgniteerG"(tnirp.tuo.metsyS{)sgra ][gnirtS(niam diov citats cilbup{C ssalc cilbup

```

For the `online compiler` i had to change the `class` name from `C` to `Main`

Try it online!

# Answer
> 0 votes
# T-SQL, 52 bytes

```
PRINT'Greetings, Planet!'--'!tenalP ,sgniteerG'TNIRP

```

Not much different from other answers, but didn't see another SQL-based solution.

`--` is an in-line comment in T-SQL, `PRINT` is one byte shorter than `SELECT`.

# Answer
> 0 votes
# Pip, ~~42~~ 40 bytes

```
"!tenalP ,sgniteerG""Greetings, Planet!"

```

Try it online!

Pip prints the last expression in a file

# Answer
> 0 votes
## Julia (1.2), 41 bytes

```
"!tenalP ,sgniteerG";"Greetings, Planet!"

```

### Example

```
julia> print("!tenalP ,sgniteerG";"Greetings, Planet!")
"Greetings, Planet!"

```

### Explanation

Putting a semicolon on the end of an expression makes the expression not output anything.

# Answer
> 0 votes
# ink, 38 bytes

```
Greetings, Planet!//!tenalP ,sgniteerG

```

Try it online!

# Answer
> 0 votes
# Fig, \\$29\log\_{256}(96)\approx\\$ 23.87 bytes

```
"H>YB_@Pm*xnJD"DJnx*mP@_BY>H"

```

Try it online!

```
"H>YB_@Pm*xnJD"DJnx*mP@_BY>H"
"H>YB_@Pm*xnJD"               # The string "H>YB_@Pm*xnJD"
               DJnx*mP@_BY>H" # Compressed string "Greetings, Planet!"

```

---
Tags: code-golf, source-layout, palindrome, hello-world
---