title: I'm a palindrome. Are you?

text:
# Question
Title: I'm a palindrome. Are you?
> There have been a couple of previous attempts to ask this question, but neither conforms to modern standards on this site. Per discussion on Meta, I'm reposting it in a way that allows for fair competition under our modern rulesets.

## Background

A is a string that "reads the same forwards and backwards", i.e. the reverse of the string is the same as the string itself. We're not talking about "convenient palindromes" here, but a strict character-by-character reversal; for example, `()()` is not a palindrome, but `())(` is.

## The task

Write a program or function that takes a string *S* (or the appropriate equivalent in your language) as input, and has one output *Q* (of a type of your choice). You can use any reasonable means to take the input and provide the output.

* When the input *S* is a palindrome, the output *Q* should have a value *A* (that is the same for any palindromic *S*).
* When the input *S* is not a palindrome, the output *Q* should have a value *B* (that is the same for any non-palindromic *S*).
* *A* and *B* must be distinct from each other.

Or in other words: map all palindromes to one value, and all non-palindromes to another.

Additionally, the program or function you write must be a palindrome itself (i.e. its source code must be palindromic), making this a challenge.

## Clarifications

* Although `true` and `false` are obvious choices for *A* and *B*, you can use any two distinct values for your "is a palindrome" and "isn't a palindrome" outputs, which need not be booleans.
* We're defining string reversal at the *character* level here; `éé` is palindromic regardless of whether the program is encoded in UTF-8 or Latin-1, even though it's not a palindromic sequence of octets after UTF-8 encoding.
* However, even if your program contains non-ASCII characters, it only needs to work for ASCII input. Specifically, the input *S* will only contain printable ASCII characters (including space, but not including newline). Among other things, this means that if you treat the input as a sequence of bytes rather than a sequence of characters, your program will still likely comply with the specification (unless your language's I/O encoding is *very* weird). As such, the definition of a palindrome in the previous bullet only really matters when checking that the program has a correct form.
* Hiding half the program in a comment or string literal, while being uncreative, is legal; you're being scored on length, not creativity, so feel free to use "boring" methods to ensure your program is a palindrome. Of course, because you're being scored on length, parts of your program that don't do anything are going to worsen your score, so being able to use both halves of your program is likely going to be helpful if you can manage it.
* Because the victory criterion is measured in bytes, you'll need to specify the encoding in which your program is written to be able to score it (although in many cases it will be obvious which encoding you're using).

## Victory criterion

Even though the program needs to be a palindrome at the character level, we're using bytes to see who wins. Specifically, the shorter your program is, measured in bytes, the better; this is a challenge. In order to allow submissions (especially submissions in the same language) to be compared, place a byte count for your program in the header of your submission (plus a character count, if it differs from the number of bytes).

# Answer
# Brachylog (2), 3 bytes in Brachylog's codepage

```
I↔I

```

Try it online!

This is a full program that takes input via standard input (using Brachylog's syntax for constants, i.e. strings are enclosed in double quotes), and outputs via standard output. The outputs are `true.` for a palindromic input, and `false.` for a non-palindromic input.

Not only is this program palindromic, it also has left/right (and probably in some fonts up/down) mirror symmetry.

## Explanation

In Brachylog, capital letters mark points in the program which have identical values; this is used almost like an electrical circuit to carry information from one part of the program to another. One consequence of this is that if you enclose a command between an identical pair of capital letters, you're effectively asserting that the command's input and output are the same. Brachylog implicitly takes input, so in this case we're also asserting that the input to the command is the same as the input to the program. In this program, we're using the command , which reverses things (in this case, strings); so the program effectively asserts that the input is the same forwards and backwards.

A full program (as opposed to a function) in Brachylog returns a boolean, `false.` if there's no way to make all the assertions in the program correct at once, or `true.` if the assertions in the program are all compatible with each other. We only have one assertion here – that reversing the input does not change it – so the program acts as a palindrome checker.
> 139 votes

# Answer
# Pyth, 3 bytes

```
_I_

```

Returns *True* or *False*.

Try it online!

### How it works

```
  _  Reverse the input.
_I   Invariant-reverse; test if the reversed input is equal to its reverse.

```
> 57 votes

# Answer
# Python, 39 bytes

```
lambda s:s[::-1]==s#s==]1-::[s:s adbmal

```

Try it online!

Boring, but if there is shorter in Python it will be impressive.
> 50 votes

# Answer
# Jelly, 5 bytes

```
ḂŒ
ŒḂ

```

Returns **1** or **0**. The first line is an unexecuted helper link, the second line calls the palindrome test.

Try it online!
> 35 votes

# Answer
# Jelly, 5 bytes

```
⁼ṚaṚ⁼

```

Try it online!

Equals reverse and reverse equals.

Or the more efficient yet less aesthetically pleasing:

```
⁼Ṛ
Ṛ⁼

```

or

```
Ṛ⁼
⁼Ṛ

```
> 25 votes

# Answer
# Haskell, ~~87~~ ~~85~~ ~~44~~ 34 bytes

```
p=(==)<*>reverse--esrever>*<)==(=p

```

Explanation: `((->) a)` is an instance of Applicative (thanks @faubiguy), with `<*>` defined as

```
(<*>) f g x = f x (g x)

```

So by substituting in the arguments one can see why this works.
> 24 votes

# Answer
# 05AB1E, 3 bytes

Code:

```
ÂQÂ

```

Explanation:

```
Â     # Bifurcate (duplicate and reverse the duplicate) implicit input
 Q    # Check if equal
  Â   # Bifurcate the result

```

Uses the **CP-1252** encoding. Try it online!
> 23 votes

# Answer
## Mathematica, 23 bytes

```
QemordnilaP;PalindromeQ

```

Not very interesting, but for the sake of completeness...

The above is a `CompoundExpression` which evaluates to `PalindromeQ`, a built-in that solves the challenge. `QemordnilaP` is simply an undefined identifier, which is ignored because of the `;`.
> 23 votes

# Answer
# PHP, 55 bytes

```
<?=strrev($s=$argv[1])==$s;#;s$==)]s[TEG_$=s$(verrts=?<

```

Try it online!
> 19 votes

# Answer
# MATL, 7 bytes

```
tPX=XPt

```

Try it online!

Returns \[1; 1\] for palindromic input and \[0; 0\] otherwise.

```
t       % duplicate the input
P       % reverse the second string
X=      % check the two strings are exactly equal (returns 0 or 1)
XP      % flip array (does nothing)
t       % duplicate the answer, giving either [1;1] or [0;0]
        % (implicit) convert to string and display

```
> 17 votes

# Answer
# Pip, ~~12~~ 11 bytes

Now comment-free!

```
x:RVaQaVR:x

```

Takes input as a command-line argument; outputs `1` for palindrome, `0` for non-palindrome. Try it online!

The core of what we want to do is `RVaQa`: `reverse(a) string-equals a`. The code `x:RVaQa` calculates this result and assigns it to `x`. Then `VR:x` assigns the value of `x` to the variable `VR`. Since this assignment is the last statement in the program, its value is also autoprinted. Voila!

For a previous interesting version using some undefined behavior, see the revision history.
> 16 votes

# Answer
# Perl 6, 25 bytes/chars utf8

```
{.flip eq$_}#}_$qe pilf.{

```

Try it
> 13 votes

# Answer
## R, ~~111~~ 103 bytes

```
all((s<-el(strsplit(scan(,"",,,"\n"),"")))==rev(s))#))s(ver==)))"",)"n\",,,"",(nacs(tilpsrts(le-<s((lla

```

Not the most original answer. `#` is the comment character in **R**

**Ungolfed:**

```
all((s<-el(strsplit(scan(,"",,,"\n"),"")))==rev(s))
#
))s(ver==)))"",)"n\",,,"",(nacs(tilpsrts(le-<s((lla

```

The character string from `scan` is converted into raw bytes thanks to the `charToRaw` function. These raw bytes are compared one-by-one to their counterparts from the `rev()` function, which reverses the order of its argument. The output of this part is a vector of `TRUE` and/or `FALSE`.
The `all` function then outputs `TRUE` if all those elements are `TRUE`

Here, `"\n"` in the `scan` function is necessary for inputs with more than one word.

### Previous answer (byte-wise), **81 bytes**

```
function(s)all((s=charToRaw(s))==rev(s))#))s(ver==))s(waRoTrahc=s((lla)s(noitcnuf

```

with *\- 24 bytes* thanks to @rturnbull.
> 10 votes

# Answer
## GNU sed, ~~64~~ 59 + 1(r flag) = 60 bytes UTF-8

Took me a while to come up with a sed answer that is not using a comment section to make the code a palindrome. Instead, I use the `c` command that would print the first half of the code in reverse order, only I make sure this instruction is not reached.

```
:;s:^(.)(.*)\1$:\2:;t;/../c1
d
1c/../;t;:2\:$1\)*.().(^:s;:

```

The script prints **`1`** if the input string is not a palindrome (think of it as giving an error). If the string is a palindrome, then **no output** is given (think of it as exiting successfully).

**Run examples:** or **Try it online!**

```
me@LCARS:/PPCG$ sed -rf palindrome_source.sed <<< "level"
me@LCARS:/PPCG$ sed -rf palindrome_source.sed <<< "game"
1

```

**Explanation:**

```
:                              # start loop
s:^(.)(.*)\1$:\2:              # delete first and last char, if they are the same
t                              # repeat if 's' was successful
/../c1                         # if at least 2 chars are left, print 1. 'c' reads
                               #till EOL, so next command must be on a new line.
d                              # delete pattern space. This line must be a
                               #palindrome itself, and must end the script.
1c/../;t;:2\:$1\)*.().(^:s;:   # (skipped) print first half of code in reverse
                               #order. Everything after 'c' is treated as string.

```
> 10 votes

# Answer
# RProgN, 11 bytes

```
~]S.E E.S]~

```

The first half of this does all the heavy lifting, and by a convenience of RProgN, the second half is a No-op.

```
~]S.E E.S]~
~           # Treat the word as a Zero Space Segment
 ]          # Duplicate the top of the stack
  S.        # Reverse the top of the stack
    E       # Compare if these values are equal
      E.S]~ # A no-op, because the ~ is at the end of the word, not the start.

```

Try it online!
> 9 votes

# Answer
## Alice, 19 bytes

```
/@.nzRoi\
\ioRzn.@/

```

Try it online!

Prints `Jabberwocky` for palindromes and nothing for non-palindromes. Works for arbitrary UTF-8 input.

### Explanation

Since this is a string processing task, Alice will have to operate in Ordinal mode to solve it. That in turn means that the instruction pointer has to move diagonally, and therefore we need at least two lines so that the IP can bounce up and down. The linefeed in such a program makes for a good position to place the middle character of the palindrome. That means the second line needs to be the reverse of the first. But since we're only executing every other character on each line, if we make sure that the line-length is odd, the reverse of the code will neatly fit into its own gaps. The only character that isn't used at all is the backslash, but since it was arbitrary I chose it to make the program look nice and symmetric.

So anyway, the actual relevant code is this:

```
/ . z o
 i R n @

```

Which is executed in a zigzag from left to right.

```
/   Reflect the IP southeast, enter Ordinal mode.
i   Read all input as a single string.
.   Duplicate the input.
R   Reverse the copy.
z   Pop the reverse Y and the original X. If X contains Y, drop everything
    up to its first occurrence. Since we know that X and Y are the same length,
    Y can only be contained in X if X=Y, which means that X is a palindrome.
    So this will result in an empty string for palindromes and in the non-empty
    input for non-palindromes.
n   Logical NOT. Replaces non-empty strings with "", and empty strings with
    "Jabberwocky", the "default" truthy string.
o   Output the result.
@   Terminate the program.

```
> 9 votes

# Answer
## Retina, 53 bytes

Byte count assumes ISO 8859-1 encoding.

```
$
¶$`
O$^`\G.
»
D`
M$`^.+$
$+.^`$M
`D
»
.G\`^$O
`$¶
$

```

Try it online!

I'm pretty sure this isn't optimal yet (the `»` line seems particularly wasteful, and I have a 45-byte solution that is palindromic except for one character), but I guess it's a start.
> 8 votes

# Answer
# Haskell, 34 bytes

```
f=(==)=<<reverse--esrever<<=)==(=f

```

Try it online! Call with `f "some string"`, returns `True` or `False`.

The `=<<` operator on functions works like `f=<<g = \s -> f (g s) s`, so the code is equivalent to `f s=s==reverse s`, which, as I just noticed, would result in the same byte count.

---

**Version without comment:** (49 bytes)

```
e x y=x/=y
p=e=<<reverse
esrever<<=e=p
y=/x=y x e

```

Try it online!

Call with `p "some string"`. This outputs `False` if the given string **is** a palindrome, and `True` if it's **not** a palindrome.

**Explanation:**

I found this comment free palindrome by starting with the comment version and replacing the the comment with a new line:

```
p=(==)=<<reverse
esrever<<=)==(=p

```

The second line fails because the parenthesis do not match, so we need to get rid of them. If we had a function `e` which checks for equality, then

```
p=e=<<reverse
esrever<<=e=p

```

will both compile with the second line defining an infix-operator `<<=` which takes two arguments `esrever` and `e` and returns the function `p`.

To define `e` as the equality function one would normally write `e=(==)`, but `)==(=e` will again not compile. Instead we could explicitly take two arguments and pass them to `==`: `e x y=x==y`. Now the reversed code `y==x=y x e` compiles but redefines the `==` operator, which causes the definition `e x y=x==y` to fail. However if we switch to the inequality operator `/=`, the reversed definition becomes `y=/x=y x e` and defines a `=/` operator which does not interferes with the original `/=` operator.
> 7 votes

# Answer
# OIL, 178 bytes

Reads an input, explodes it, slowly adds its length (through incrementing and decrementing) to the address to know to the address after the string, jumps to a different part of code (in the middle), reverses the band direction, implodes the string again, and checks whether it's the same as the original string. TL;DR: It's a pain, as usual.

Outputs `40` if the string isn't a palindrome, `0` if it is.

```
5
0
12
0
40
1
40
2
1
40
34
10
2
3
22
16
9
2
8
35
6
11
6
37

3
4
4
27
26
0
1
10
1

40
13
2
31
04

1
01
1
0
62
72
4
4
3

73
6
11
6
53
8
2
9
61
22
3
2
01
43
04
1
2
04
1
04
0
21
0
5

```
> 6 votes

# Answer
# Japt, ~~7~~ 2 bytes

```
êê

```

Run it

### Old solution:

```
U¥UwU¥U

```

Try it online!

### Explanation

```
U¥UwU¥U
U¥        U is the input, ¥ is a shortcut for ==
  Uw      w is a reverse function.
    U¥U   This calculates U == U (always true), but the result is ignored
          because w does not look at its arguments.

```

Japt doesn't escape functions unless a closing parenthesis (or space) is reached.

This can be re-written: `U¥Uw(U¥U)``U¥Uw``U==Uw`. In Japt, the parenthesis left out at the begining and end of a function is auto-inserted.
> 5 votes

# Answer
# Java 8, ~~92~~ 90 bytes

This is a comment version. If a string contains its reverse, then it is a palindrome (`true`) otherwise it is not (`false`).

```
s->s.contains(new StringBuffer(s).reverse())//))(esrever.)s(reffuBgnirtS wen(sniatnoc.s>-s

```

---

Try it online!

**Update**

* **-2** \[18-04-05\] Switched to contains. Thanks to *@Kevin Cruijssen*!
* **-2** \[17-02-20\] Removed `;`'s
* **-16** \[17-02-22\] Auto convert
> 5 votes

# Answer
# Dyalog APL, 6 bytes

```
⌽≡⊢⊢≡⌽

```

Try it online!
> 5 votes

# Answer
# , 9 bytes

```
[:-.|.-:[
```

Attempt This Online!

Lolwut. I was fiddling with various arrangements and adverb trains until I realized `[:` in trains is a thing, and `-.` (boolean negation) is perfectly OK thanks to the permissive output format. Returns 0 if the input is palindrome and 1 otherwise.

```
[: -. (|. -: [)
       |. -: [   Reverse matches identity (classic palindrome check)
[: -.            Boolean negation on the result

```

---

# , 11 bytes

```
]&.|:-:|.&]
```

Attempt This Online!

Wins against the existing comment abuse solution. Uses a similar trick to this answer to "I reverse the source, you reverse the input!".

Many of J's built-ins have inflections `.` and `:`, which are always treated as the suffix of a larger token. So the function above tokenizes as `] &. |: -: |. & ]`. And `&.` and `&` are conjunctions, which consume two things on both sides to form a single verb. Finally, `verb1 verb2 verb3` is a verb train; when given an argument `y`, it evaluates to `(verb1 y) verb2 (verb3 y)`.

```
] &. |: -: |. & ]
] &. |:             Identity under transpose: returns the input unchanged
           |. & ]   Reverse over identity: returns the input reversed
        -:          Match: tests if the two sides are identical

```
> 5 votes

# Answer
# Bash \+ Unix utilities, 49 bytes

```
[ "$1" = "`rev<<<$1`" ] # ] "`1$<<<ver`" = "1$" [

```

Input is passed as an argument.

Output is returned in the result code -- 0 for a palindrome, 1 for a non-palindrome.

*Maybe someone can do better and not just rely on a comment to make the code itself palindromic.*

Try it online!
> 4 votes

# Answer
# Javascript, 64 bytes

```
f=s=>s==[...s].reverse().join``//``nioj.)(esrever.]s...[==s>=s=f

```

Call function `f` with string

```
f("abba") // returns true
f("abab") // returns false

```
> 4 votes

# Answer
# Java - ~~171~~ ~~169~~ 160 bytes

```
int q(String s){return s.equals(new StringBuffer(s).reverse().toString())?1:2;}//};2:1?))(gnirtSot.)(esrever.)s(reffuBgnirtS wen(slauqe.s nruter{)s gnirtS(q tni

```

The comment at the end is to make it a palindrome. Returns `P(alindrome)` when the input is palindrome and `N(ot)` when not.

Ungolfed version:

```
int q(String s) {
    return s.equals(new StringBuffer(s).reverse().toString()) ? 'P' : 'N';
}//};'N':'P'?))(gnirtSot.)(esrever.)s(reffuBgnirtS wen(slauqe.s nruter{)s gnirtS(q tni

```

2 bytes saved thanks to @DLosc

Thanks to @Olivier Grégoire for pointing out the incorrect amount of bytes! Fixed now
> 4 votes

# Answer
# Jelly, 4 bytes

```
ḂŒŒḂ

```

Try it online!

Although this loses to the modern `UƑU`, I figured it may be of historical interest to note that Dennis's solution could have been only 4 bytes. Thanks to a quirk of the parser, any undefined characters--such as `Œ` outside a valid digraph--act equivalent to *two* newlines; as such, removing the newline yields a functionally identical solution (if not particularly forward-compatible, should `ŒŒ` ever hypothetically be added).
> 4 votes

# Answer
# Actually, 5 bytes

```
;R=R;

```

Try it online!

The truthy output is `[1]\n[1]`, and the falsey output is `[]\n[]` (in both outputs, `\n` represents a literal newline).

Explanation:

```
;R=R;
;R=    duplicate input, reverse one copy, test equality (the main palindrome-testing part)
   R   range(1, x+1) - if palindrome, this pushes [1], else it pushes []
    ;  duplicate

```
> 3 votes

# Answer
# C++, 154 Bytes

```
int m(){std::string g,p="";g=p;std::reverse(p.begin(),p.end());return g==p;}//};p==g nruter;))(dne.p,)(nigeb.p(esrever::dts;p=g;""=p,g gnirts::dts{)(m tni

```

I have to say, the reverse statement was costly, but I can't imagine much I can do to change that. Being able to cut out the std:: symbols would save me around 10 characters, but "using namespace std;" is quite a few more.

I suppose C++ wasn't really meant for brevity.
> 3 votes

# Answer
## Prolog, 44 bytes

```
p-->[]|[_]|[E],p,[E].%.]E[,p,]E[|]_[|][>--p

```

This uses definite clause grammars. It is actually a full context free grammar:

```
p -->
      []            % the empty string
   |                % or
      [_]           % a one character string
   |                % or
      [E],          % one character, followed by
      p,            % a palindrome, followed by
      [E].          % that same character

```

Usage:

```
?- phrase(p,"reliefpfeiler").
true

?- phrase(p,"re").
false.

```
> 3 votes

# Answer
# MathGolf, ~~2~~ 3 bytes

```
x=x

```

Try it online!

## Explanation

Nothing fancy here, just some usage of implicit input. `x` reverses strings. Since the stack is empty, the input is reversed and placed on the stack. `=` checks for equality for the top two elements on the stack. Since the stack has only one element, the other element is fetched from the input, which is the original string. If they are equal, we get `1`, otherwise we get a `0`. `x` also works on integers, but since both `0` and `1` are 1-digit numbers, they remain unchanged.

EDIT: made the code a palindrome thanks to Lyxal's comment.
> 3 votes

# Answer
# Dyalog APL, 21 Bytes

I decided to avoid a comment-based solution, and ended up with something pretty ugly. Instead of commenting out the second half of my code, I keep it in and allow the resulting syntax error to be part of my output.

```
A←⍞⋄0∊A=⌽A⋄A⌽=A∊0⋄⍞←A

```

This prompts the user to enter a string, and prints

```
0
SYNTAX ERROR: The function requires a left argument
      A←⍞ ⋄ 0∊A=⌽A ⋄ A⌽=A∊0 ⋄ ⍞←A

```

If the input is a palindrome, and prints

```
1
SYNTAX ERROR: The function requires a left argument
      A←⍞ ⋄ 0∊A=⌽A ⋄ A⌽=A∊0 ⋄ ⍞←A

```

If the input is not a palindrome.

A simple comment based solution would be to replace the middle character () with the comment symbol ():

```
A←⍞⋄0∊A=⌽A⍝A⌽=A∊0⋄⍞←A

```

This does the same as above but doesn't include the syntax error in the output.

Here's an ungolfed version:

```
A←⍞          ⍝ prompt user for input, store in variable A
⋄             ⍝ statement separator
0∊A=⌽A       ⍝ return '0' if A is equal to A reversed (`⌽A`). Otherwise return '1'
⋄             ⍝ statement separator
A⌽=A∊0⋄⍞←A   ⍝ reverse of preceding code, throws a syntax error

```
> 2 votes

# Answer
# CJam, 13 bytes

```
l_W%=e#e=%W_l

```

## Explanation:

```
l_W%=e#e=%W_l
l_            e#Read input twice
  W%          e#Reverse one input
    =         e#Test for equality
     e#e=%W_l e#Comment to be a palindrome

```

## Example:

```
> l_W%=e#e=%W_l
l_W%=e#e=%W_l
1

> l_W%=e#e=%W_l
Hi
0

> l_W%=e#e=%W_l
hh
1

```
> 2 votes

# Answer
# J, 15 bytes, 15 characters

```
-:|.NB. .BN.|:-

```

Returns 1 if palindrome, 0 if not.

**Output:**

```
   f '())('
1
   f 'nope'
0

```

**Explanation:**

```
-:    NB. "Match" verb, checks for equality
|.    NB. Reverses the string

```
> 2 votes

# Answer
# Ruby, 39 35 chars

```
->s{s.reverse==s}#}s==esrever.s{s>-

```
> 2 votes

# Answer
# Golfscript, 11 bytes

Bonus for the bytecount being a palindrome as well.

```
.-1%=#=%1-.

```

Duplicate, reverse, compare. Outputs `1` for palindromes and `0` for non-palindromes.
> 2 votes

# Answer
# Ruby `-n`, 31 bytes

```
p$_==$_.reverse#esrever._$==_$p

```

Try it online!

A full program with implicit input (`-n`) turns out to be slightly shorter than lambda.
> 2 votes

# Answer
# Jelly, 3 bytes

```
UƑU

```

Try it online!

Added for the sake of completeness. This uses the fairly new quick `Ƒ`, which checks whether the argument is the same as the result of the atom being applied. Here, the atom is `U`, which reverses the argument. The quicklink  returns either **1** for palindromes, or **0** otherwise. The second `U` has no effect on either integer, so leaves it as is.
> 2 votes

# Answer
# , 71 bytes

```
any(rev(x<-utf8ToInt(scan(,"")))-x)#)x-)))"",(nacs(tnIoT8ftu-<x(ver(yna

```

Try it online!

Comments to make it a palindrome. Returns `FALSE` if the input is a palindrome, `TRUE` otherwise. Could save 2 bytes off the palindrome using `sd` if we were guaranteed to have an input size \>1.

Interpreting liberally this portion of the asnwer

> if you treat the input as a sequence of bytes rather than a sequence of characters, your program will still likely comply with the specification

would lead to:

### , 43 bytes

```
any(x<-scan()-rev(x))#))x(ver-)(macs-<x(yna

```

Try it online!
> 2 votes

# Answer
## , 3 bytes

Pretty trivial, reverse & check equality & reciprocal. (I definitely beat Jelly by tying with Pyth.)

```
_=_

```

## Explanation

```
_   Reverse the implicitly inputted string
 =  Check whether this reversed string is equal to the original string
  _ Negate this string

```
> 2 votes

# Answer
# Google Sheets, ~~171 167~~ 163

Input is in `A1`.

```
=-IFERROR(JOIN(,ArrayFormula(MID(A1,SEQUENCE(LEN(A1),1,LEN(A1),-1),1)))=""&A1,1)&"&)1,1A&""=)))1,)1-,)1A(NEL,1,)1A(NEL(ECNEUQES,1A(DIM(alumroFyarrA,(NIOJ(RORREFI-=

```
* Palindrome: `-1&)1A&"=)))1,)1-,)1A(NEL,1,)1A(NEL(ECNEUQES,1A(DIM(alumroFyarrA,(NIOJ(RORREFI-=`
* Not: `0&)1A&"=)))1,)1-,)1A(NEL,1,)1A(NEL(ECNEUQES,1A(DIM(alumroFyarrA,(NIOJ(RORREFI-=`

## How it works:

1. Compare a string with its reverse. I thought it necessary to handle the empty string as well, so I added `IFERROR()` for the `MID()`.
2. Coerce to number with `-`. 1 becomes -1, 0 stays 0.
3. The only requirement was two distinct outputs, so just concatenate the program's reverse to the end.
4. We also exploit the fact that Sheets closes quotes and parens at the end.
5. The center of the palindrome is the `&"&`
> 2 votes

# Answer
# 05AB1E, 3 bytes

```
RQR

```

Try it online!

```
RQR  # full program
 Q   # is...
     # implicit input...
 Q   # equal to...
     # implicit input...
R    # reversed...
 Q   # ? (1 if yes, 0 if no)
  R  # reverse top of stack (no-op since both 1 and 0 are palindromes)
     # implicit output

```
> 2 votes

# Answer
# x86\_64 machine code, 49 bytes

Uses System V ABI calling convention (specifically first arg in RDI, return in RAX, DF cleared by caller).

Hexdump:

```
00000000: 31c0 575e 31c9 f7d1 f2ae 4883 ef02 803e  1.W^1.....H....>
00000010: 0074 05a6 74f4 ffc0 c3c0 fff4 74a6 0574  .t..t.......t..t
00000020: 003e 8002 ef83 48ae f2d1 f7c9 315e 57c0  .>....H.....1^W.
00000030: 31                                       1

```

Try it online!

Explanation:

```
0000000000401020 <test_palindrome>:
  401020:   31 c0                   xor    eax,eax ; clear eax
  401022:   57                      push   rdi
  401023:   5e                      pop    rsi ; copy rdi to rsi

  ; get end of string (by SCASing rdi to find 0)
  401024:   31 c9                   xor    ecx,ecx
  401026:   f7 d1                   not    ecx
  401028:   f2 ae                   repnz scas al,BYTE PTR es:[rdi]

  ; addr of start is in rsi, addr of end (past \0) is
  ; in rdi, so we subtract 2 from rdi. Thankfully this is needed below too,
  ; so we can combine the two steps into one.

  ; Now, we loop, incrementing rsi and decrementing rdi until [rsi] == '\0'
000000000040102a <testp_loop>:
  40102a:   48 83 ef 02             sub    rdi,0x2 ; Shortest way to do this?

  40102e:   80 3e 00                cmp    BYTE PTR [rsi],0x0 ; [rsi] == '\0'?
  401031:   74 05                   je     401038 <retl> ; If so, str is a palindrome (ret0)

  ; Check that [rsi] == [rdi]
  401033:   a6                      cmps   BYTE PTR ds:[rsi],BYTE PTR es:[rdi] ; Auto increments rsi and rdi, so rdi needs subtracting by 2.
  401034:   74 f4                   je     40102a <testp_loop> ; If so, keep looping.

  ; Otherwise, str is not a palindrome (ret1)
  401036:   ff c0                   inc    eax

0000000000401038 <retl>:
  401038:   c3                      ret

  ; <nonsense to make code a palindrome>
  401039:   c0 ff f4 74 a6 05 74 00 3e 80 02 ef 83 48 ae f2 d1 f7 c9 31 5e 57 c0 31

```
> 2 votes

# Answer
## QBIC, 17 bytes

```
;?A=_fA|#|Af_=A?;

```

Uses a boring comment-like ttrick to make the code a palindrome. Explanation:

```
;         Get a string literal from the cmd prompt
?         Print -1 for true and 0 for false in the following comparison
A=        Is A equal to
_fA|      A reversed?

#         Start a 'silent' string literal: This only forces the creation of string B
          with the following text, but doesn't inject a reference to B$ here.
|Af_=A?;  Code, reversed, as a string literal.

```
> 1 votes

# Answer
# AppleScript, 146 bytes

*clutch*

```
set x to(display dialog""default answer"")'s characters--
x=reverse of x--x fo esrever=x
--sretcarahc s')""rewsna tluafed""golaid yalpsid(ot x tes

```

This should be fairly obvious.
> 1 votes

# Answer
# Common Lisp, 104 bytes

```
(lambda(s)(format t"~:[F~;T~]"(equal(reverse s)s)));;)))s)s esrever(lauqe("]~T;~F[:~"t tamrof()s(adbmal(

```

Abusing idea for commenting out part of code from comments under question.
> 1 votes

# Answer
**Javascript, 78 bytes**

```
(s=>s==s.split('').reverse().join(''))//))''(nioj.)(esrever.)''(tilps.s==s>=s(

```

This is the classic `.split`, `.reverse` and `.join` routine.

Another (longer, but I like it more) 104 bytes solution would be

```
(s=>!s.split('').find((a,i,l)=>a!==l[l.length-i-1]))//))]1-i-htgnel.l[l==!a>=)l,i,a((dnif.)''(tilps.s!>=s(

```
> 1 votes

# Answer
# Pyth - 3 bytes

An alternative 3 byte solution. Palindromes give `-1` and non-palindromes give `0`.

```
_q_

```

Test Suite.

A few more 3 byte solutions:

```
_/_
_}_

```
> 1 votes

# Answer
# Scala - 58 bytes

```
def p(s:String)=s.reverse==s//s==esrever.s=)gnirtS:s(p fed

```

Example -

```
p("abba") //returns true

p("aabb") //returns false

```
> 1 votes

# Answer
# Java (with regex), 134 bytes

```
s->s.matches("|(?:(.)(?<=(?=^.*?(\\1\\2?)$).*))+(?<=(?=^\\2$).*)")//)")*.)$2\\^=?(=<?(+))*.)$)?2\\1\\(?*.^=?(=<?().(:?(|"(sehctam.s>-s

```

Credits where due

## Testing

```
import java.util.function.*;

class Ideone {
  static Predicate<String> isPalindrome =
    s->s.matches("|(?:(.)(?<=(?=^.*?(\\1\\2?)$).*))+(?<=(?=^\\2$).*)")//)")*.)$2\\^=?(=<?(+))*.)$)?2\\1\\(?*.^=?(=<?().(:?(|"(sehctam.s>-s
    ;

  public static void main (String[] args) throws java.lang.Exception {
    testPalindrome("", true);
    testPalindrome("x", true);
    testPalindrome("xx", true);
    testPalindrome("xy", false);
    testPalindrome("xyx", true);
    testPalindrome("xxx", true);
    testPalindrome("xxyx", false);
    testPalindrome("racecar", true);
    testPalindrome("step on no pets", true);
    testPalindrome("aManaPlanaCanalPanaMa", true);
    testPalindrome("this is impossible", false);
  }

  static void testPalindrome(String s, boolean expected) {
    if (isPalindrome.test(s) == expected) {
      System.out.println("OK");
    } else {
      System.out.printf("NOK: str=\"%s\", expected=%b%n", s, expected);
    }
  }
}

```

Test it yourself!
> 1 votes

# Answer
# Scala, 50 bytes

Failed to *not* write a comment based solution so this is it:

```
(s:String)=>s.reverse==s//s==esrever.s>=)gnirtS:s(

```
> 1 votes

# Answer
# Common Lisp, 61 bytes

```
(lambda(n)(equal(reverse n)n));))n)n esrever(lauqe()n(adbmal(

```

Try it online!

Outputs `T` when the string is palindrome, `NIL` otherwise.
> 1 votes

# Answer
# Pyt, 1 byte

Try it online!

```
   implicit input
₽  palindromic test
   implicit output

```

## Previous answer

before I knew that 1 byte solutions were allowed

```
₽ƥƥ₽

```

Try it online!

```
₽ checks for palindromicness <sup>(is that a word?)</sup>
ƥ prints the answer
ƥ prints nothing
₽ checks the palindromicness of nothing
```
> 1 votes

# Answer
# Japt, 2 bytes

```
êê

```

Try it

`ê` on its own in Japt creates a palindrome but, when passed a string as an argument (which the second `ê` is implicitly cast to in this case), it instead tests if a string is palindromic.
> 1 votes

# Answer
# Add++, 13 bytes

```
L,dbR=;=Rbd,L

```

Try it online!
> 1 votes

# Answer
# C (gcc), 118 bytes

Can sadly not come up with any solution without the boring comment approach.

```
f(char*s){char*t=s+strlen(s);for(;*s&&*s++==*--t;);s=!*s;}//};s*!=s;);t--*==++s*&&s*;(rof;)s(nelrts+s=t*rahc{)s*rahc(f

```

Try it online!
> 1 votes

# Answer
# Reflections, 125 bytes

```
  _1=1\ /1#\ /+#_
      >~<  >~<
        (0//0)
      \ / >_ / _> / \
)0//0(
<~>  <~>
 _#+/ \#1/ \1=1_

```

Test it!

Prints code point 0x04 as true, and nothing as false. There are a few spaces after some lines.

### Explanation

The relevant part of the code is:

```
  _1=1\ /1#\ /+#_
      >~<  >~<
        (0//0)
      \ / >_ /

```
* `_` reads a line
* `1=1` copies it to stack 1
* `>~<` creates a loop over the complete stack:
    + `(0` pushes the top item to stack 0
* now stack 0 contains the reverse, and stack 1 the original
* `1` moves stack 1 to mainstack
* `>~<` loops again:
    + `0)` takes the next character from reversed
    + `>_` if original and reversed character are not equal:
        - end the program by navigating downwards, leaving the field
* `+` produces the 4
* `_` prints corresponding character
* then the program stops (leaving the field to the right)

The rest is only for palindromic source. I know this is boring.
> 1 votes

# Answer
# Perl 5, 29 bytes

```
$_=reverse=~$_#_$~=esrever=_$

```

Requres `-p0`. Outputs `1` if the input is a palindrome, empty otherwise.

Try it online!

---

**Perl 5, 33 bytes**

```
+$_=reverse=~$_+q+_$~=esrever=_$+

```

Commentless version, requires `-p0`. Outputs `1` if the input is a palindrome, `0` otherwise.

Try it online!
> 1 votes

# Answer
# Vyxal, 3 bytes

```
Ṙ=Ṙ

```

Try it Online!

```
 =  # Equal to...
Ṙ   # Self reversed?
  Ṙ # Reverse the result

```
> 1 votes

# Answer
# Knight, 71 bytes

```
;=a=pP;=s'';Wp;=s+GpF1s=pSpF1''O?a s a?O''1FpSp=s1FpG+s=;pW;''s=;Pp=a=;

```

Input the string with a trailing newline.

Try It Online!

In case you're curious, here's the non-palindromized version of the code:

```
;=a=pP;=s'';Wp;=s+GpF1s=pSpF1''O?a s

```

Try It Online!
> 1 votes

# Answer
# Julia 1.0, 33 bytes

```
!x=reverse(x)==x#x==)x(esrever=x!

```

Try it online!

* A comment is used to make the source a palindrome
* Returns `true` for the empty string
> 1 votes

# Answer
# \[Python\], 84 bytes

```
lambda s:list(s)==list(reversed(list(s)))#)))s(tsil(desrever(tsil==)s(tsil:s adbmal

```

Pretty simple, take the string s, convert it into a list of chars and then compare that against the reversed list of chars generated from the same string.
> 0 votes

# Answer
# SmileBASIC, 109 bytes

```
INPUT P$WHILE LEN(P$)>1P=P+(POP(P$)!=SHIFT(P$))WEND?!P'P!?DNEW))P$(TFIHS=!)$P(POP(+P==P1>)$P(NEL ELIHW$P TUPNI

```

Could definitely be shorter...
> 0 votes

# Answer
# Perl 5, 69 bytes

`$_=<>;chop;print 1 if reverse eq$_#_$qe esrever fi 1 tnirp;pohc;><=_$`

Takes input via STDIN. Prints `1` if the input is a palendrome, otherwise exits.
> 0 votes

# Answer
## REXX, 78 bytes

```
arg a
b="say a=reverse(a)"
interpret b
exit
tixe
b terpretni
")a(esrever=a yas"=b
a gra

```

I thought that early exit would leave the mirrored program uninterpreted, but at least Regina REXX complains about unbalanced parentheses, hence the INTERPRET workaround.
> 0 votes

# Answer
# Kotlin, 32 bytes

*Just another "boring" solution but in Kotlin :))*

```
s.reversed()==s//s==)(desrever.s

```

Try it online!
> 0 votes

# Answer
# RProgN 2, 5 bytes

```
]iei]

```

Returns `-1\n-1` for true, `0\n0` for false.

## Explained

```
]iei]
]       # Duplicate the top of the stack.
 i      # Reverse the duplicate
  e     # Are they equal? 1 if true, 0 if false.
   i    # Inverse calculates n*-1. Redunant.
    ]   # Duplicate. Redundant.

```

Try it online!
> 0 votes

# Answer
# BASH, 52 bytes

```
[ "`rev<<<$1`" = "$1" ];$?$;] "1$" = "`1$<<<ver`" [

```

success output (run as `palpal.bash`:

```
~/workspace/golf $ bash palpal.bash "$(cat palpal.bash)"
palpal.bash: line 1: 0$: command not found
palpal.bash: line 1: 1$: command not found
palpal.bash: line 1: ]: command not found

```

failure output:

```
~/workspace/golf $ bash palpal.bash "hello"
palpal.bash: line 1: 1$: command not found
palpal.bash: line 1: 1$: command not found
palpal.bash: line 1: ]: command not found

```

notice that first output line has either a `1` or `0` which are the return code of the actual palindrome check.

It's not much better than using a comment for the second half
> 0 votes

# Answer
# C++ (gcc), 138 bytes

```
[](auto s){return equal(s.begin(),s.begin()+s.size()/2,s.rbegin());}//};))(nigebr.s,2/)(ezis.s+)(nigeb.s,)(nigeb.s(lauqe nruter{)s otua(][

```

Lambda using a builtin to check if the argument is palindromic. To make it palindromic, I had to add the entire source, reversed, in a comment. Not very creative, I know. Note that clang will not compile this.

Try it online here.
> 0 votes

# Answer
# Gol\>\<\>, 31 bytes

```
iEv
?;>l2(q1h{-
-{h1q(2l>;?
vEi

```

Try it online!

```
iEv
?;>l2(q1h{-

iEv
i    Take input as a char
 E   If the last input was EOF, pop and execute next; otherwise, skip 1
iEv  Take all input and move to next line

>l2(q1h{-?;
 l2(         Is the stack length < 2? (1 if yes, 0 otherwise)
    q        If not, skip 2 commands (consume the top)
     1h      Print 1 and halt
       {     Rotate the stack (bottom goes to the top)
        -    Difference
         ?   If zero, skip one command (consume the top)
          ;  Halt without printing anything

```
> 0 votes

# Answer
# C# (.NET Core), 110 bytes

```
s=>Console.Write(new string(s.Reverse().ToArray())==s)//)s==))(yarrAoT.)(esreveR.s(gnirts wen(etirW.elosnoC>=s

```

Try it online!
> 0 votes

# Answer
# Pascal (FPC), 139 bytes

```
uses strutils;var s:string;begin read(s);write(s=ReverseString(s))end.dne))s(gnirtSesreveR=s(etirw;)s(daer nigeb;gnirts:s rav;sliturts sesu

```

Try it online!

The program compares if the input is equal to its reverse using `ReverseString()` function from module `strutils`.

`end.` is the last part of the program. This program does not use comments because, in most cases, FPC does not care what is after `end.`, so the program without the dot is simply reversed and appended to the program itself.
> 0 votes

# Answer
# T-SQL, 70 bytes

```
SELECT IIF(s=REVERSE(s),1,0)FROM t--t MORF)0,1,)s(ESREVER=s(FII TCELES

```

Didn't see a SQL version, so here's my try. Returns 1 for a palindrome, and 0 otherwise. `IIF` is supported by SQL 2012 and later.

Input is via pre-existing table **t** with varchar field **s**, per our IO rules. The input table can include multiple rows.

The `--` in the middle is a comment character.

**Edit**: Here's a more clever version, using a strangely-named input table instead of an extended comment. Unfortunately slightly longer (**73 bytes**):

```
--"
SELECT IIF(s=REVERSE(s),1,0)FROM"MORF)0,1,)s(ESREVER=s(FII TCELES
"--

```

This requires an input table with a long strange name:

```
CREATE TABLE [MORF)0,1,)s(ESREVER=s(FII TCELES
] (s VARCHAR(999))

```

Note the return is included in the table name (*not* a recommended naming strategy for your databases, by the way).

Tables with otherwise invalid characters in their name need brackets or double-quotes around them, and the only way I could put the required quote at the beginning was to set it after a comment.
> 0 votes

# Answer
# C# (.NET Core), 94

```
s=>Console.Write(s.SequenceEqual(s.Reverse()))//)))(esreveR.s(lauqEecneuqeS.s(etirW.elosnoC>=s

```

Improves slightly on the answer from Anderson Pimentel

Try it online
> 0 votes

# Answer
# MUMPS, 36 bytes

```
r r r w r=$re(r) ; )r(er$=r w r r r

```

## Explanation

There are no reserved keywords in MUMPS; the compiler just uses context to decide if you you are referencing a routine, command, or variable.

`r` : define routine "r"

`r r` : read input and assign to variable "r"

`w r=$re(r)` : write 1 if "r" equals its reverse (`$re` is the shortened form of `$reverse`)

`; )r(er$=r w r r r` : lame comment to make palindromic

Ungolfed version:

```
palindromeRoutine
 read input
 write input=$reverse(input)

```
> 0 votes

# Answer
# GolfScript, 11 bytes

```
.0(%=1=%(0.

```

Try it online!

Outputs via error. Throws an `undefined method` error if the input is a palindrome and a `ZeroDivisionError` otherwise.
> 0 votes

---
Tags: code-golf, string, decision-problem, restricted-source, palindrome
---


title: Rarity of a String

text:
# Question
Title: Rarity of a String
**Input:** A string
**Output:** The rarity of the string, as described below.
To find the rarity of a string, follow the steps below.

* **Start** with **0**.
* **Subtract 3** for each **E, A, T, or O** in the string.
* **Subtract 2** for each **I, N, S, or H** in the string.
* **Subtract 1** for each **R, D, L, or C** in the string.
* **Add 1** for each **W, F, G, or Y** in the string.
* **Add 2** for each **K, V, B, or P** in the string.
* **Add 3** for each **J, Q, X, or Z** in the string.

**Test cases:**
Input: `"rarity"`
Output: `-9`
Input: `"aardvark"`
Output: `-8`
Input: `"quine"`
Output: `-4`
Input: `"wow"`
Output: `-1`
Input: `"why"`
Output: `0`
Input: `"puppy"`
Output: `7`
**Scoring:**
This is . The shortest answer in bytes wins!
**Clarifications:**

* The input only consists of lowercase letters.
* The input is guaranteed to be non-empty.
* For U and M, do nothing.
* The text can be in any format.

# Answer
> 6 votes
# Nibbles, 17.5 bytes (35 nibbles)

```
+.$- 3=?;$$`D7 3c2740e64a52f8f4a8d

```

A rather sneaky port of hakr14's Pyth answer: upvote that!

```
 .$                 # map across each character of input
      ?;$$          #   get index+1 in alphabet
     =              #   get element at that index
          `D        #   of data value 3c2740e64a52f8f4a8d
            7       #   in base-7
   -3               #   and subtract from 3
+                   # finally, get the sum

```

---

Previously:

# Nibbles, ~~24.5~~ 24 bytes (48 nibbles)

```
+.$- 3/+?`D-26$3 4 2a4654a17c30c595a94262e628a6

```

```
+.$- 3/+?`D-26$3 4
 .$                 # map across letters of the input
        ?     $     # getting the index (or 0 if not found) of each in:
         `D         #   the data value 2a4654a17c30c595a94262e628a6
           -        #   interpreted as characters
            26      #   in base 26
                    #   (this equates to the string "bkpvfgwy  mucdlrhinsaeot")
       +       3    # add 3,
      /          4  # integer-divide by 4,
   - 3              # and subtract from 3,
+                   # and finally output the sum.

```

# Answer
> 9 votes
# 05AB1E, ~~27~~ 26 bytes

```
A2úœ•ι9η†₁Ù^Pι²Qš•èIk4÷3-O

```

Input as a list of characters.

Try it online or verify all test cases. (With `œ•...•è` replaced with `S•...•.I`, so it won't time out.)

**Explanation:**

```
A        # Push the lowercase alphabet
 2ú      # Pad it with two leading spaces
   œ     # Get a list of all permutations of this string
    •ι9η†₁Ù^Pι²Qš•
         # Push compressed integer 24022710646877664751280873208
     è   # Index it into the list of permutations to get string
         #  "aeothinscdlr  mufgwybkpvjqxz"
Ik       # Get the (0-based) index of each character of the input-list in this string
  4÷     # Integer-divide each index by 4
    3-   # Subtract each by 3
      O  # Take the sum
         # (which is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•ι9η†₁Ù^Pι²Qš•` is `24022710646877664751280873208`.

`24022710646877664751280873208` is generated by the Jelly builtin `Œ¿` (minus 1, to convert Jelly's 1-based indexing to 05AB1E's 0-based).

# Answer
> 9 votes
# Python, 63 bytes

```
lambda x:sum('inshrdlcmumuwfgykvbpjqxz'.find(c)//4-2for c in x)

```

Attempt This Online!

Port of @Neil's not yet written charcoal answer. ;-p

# Answer
> 8 votes
# K (ngn/k), ~~38~~ 37 bytes

```
+/3--4!24^"jqxzkvbpwfgymumurdlcinsh"?

```

Try it online!

Essentially a port of Kevin's 05AB1E answer.

* `24^"jqxzkvbpwfgymumurdlcinsh"?` get 0-based indices of input in this lookup string (the "missing" `"eato"` is filled with `24^`)
* `3--4!` integer divide the indices by 4, then subtract the result from 3
* `+/` take the sum (and implicitly return)

# Answer
> 8 votes
# Java 8, ~~63~~ 62 bytes

```
s->s.map(c->"␁ ␆ ␃ ␃ ␁ ␅ ␅ ␂ ␂ ␇ ␆ ␃ ␄ ␂ ␁ ␆ ␇ ␃ ␂ ␁ ␄ ␆ ␅ ␇ ␅ ␇".charAt(c-97)-4).sum()

```

Try it online.

**Explanation:**

```
s->                 // Method with character IntStream parameter and integer return-type
  s.map(c->         //  Map over each character:
     "␁ ␆ ␃ ␃ ␁ ␅ ␅ ␂ ␂ ␇ ␆ ␃ ␄ ␂ ␁ ␆ ␇ ␃ ␂ ␁ ␄ ␆ ␅ ␇ ␅ ␇"
                    //   In this String†
       .charAt(     //   Get the character at index:
               c    //    The codepoint of the current character
                -97 //    Minus 97 to convert it to a 0-based index
       )-4          //   Then subtract 4 from it
                    //   (-1 to convert the codepoint to a digit; and an additional -3)
   ).sum()          //  After the map: sum the stream together and return it

```

† This String consists only of unprintable characters. The codepoint-integers of these characters are `[1,6,3,3,1,5,5,2,2,7,6,3,4,2,1,6,7,3,2,1,4,6,5,7,5,7]` (represented above with space-delimited Control Picture unicode characters).

# Answer
> 8 votes
# Excel (ms365), ~~87~~, ~~86~~, 80 bytes

-1 Byte thanks to @DominicvanEssen

-6 Bytes thanks to @jdt

```
=SUM(MID("16331552276342167321465757",CODE(MID(A1,SEQUENCE(LEN(A1)),1))-96,1)-4)

```

# Answer
> 6 votes
# Vyxal, 26 bytes

```
«ƛ₇⇩⇧ɽ¬Ẏ₁5≬*⋎ǑṄǑz!«vḟ4ḭ3-∑

```

Try it Online!

Port of Kevin's 05AB1E answer.

## Explained (old)

*I'll rework this tomorrow when it's not 12:59am*

```
ƛ«∧Ǒ₄ẇ*§,(ε±ẏt∩⁽→«6/$vcT›h3ɾḂNJ0pi
ƛ                                   # To each character in the input
 «∧Ǒ₄ẇ*§,(ε±ẏt∩⁽→«                  #    Push the string "wfgykvbpjqxzeatoinshrdlc" - this corresponds to the groups [+1, +2, +3, -3, -2, -1]
                  6/                #    And split that string into 6 equal length pieces.
                    $vcT›h          #    Get the 1-based index of where the character is in the +- grouped string (u and m will return 0)
                          3ɾḂNJ0p   #    The list [0, 1, 2, 3, -3, -2, -1]
                                 i  #    Indexed by the previous number
# At the end of execution, the `s` flag sums the list of numbers

```

# Answer
> 6 votes
# \>\<\> (Fish), ~~62~~ ~~60~~ 56 bytes

Rare case where \>\<\> beats python

* -2 bytes because I can't be beaten by Java, and by poluting the stacks.
* -4 bytes by reading from the stack instead of jumping, which eliminates the delete stack loop

```
0i:0(?^'a'-1g'3'-+00.
05220441165231056210354646
   ;n~\

```

Experience it in full HD\* \*only if you have a full HD monitor, you have anti-aliasing enabled in your browser, you are zoomed out 50%, and the stars are aligned.

## Explanation

Top row: Take input, subtract it from "a" to get the index at the bottom. If the input is negative we go up. Read the letter from the middle row, subtract the char code of 3 then add it to accumulator.

Middle row: Raw data on char values.

Print result and exit

# Answer
> 5 votes
# Python, ~~80~~ 79 bytes

* -1 byte thanks to @Mukandan314

```
lambda x:sum(map(int,x.translate('0'*98+'5220441165231056210354646')))-len(x)*3

```

Attempt This Online!

# Answer
> 5 votes
# Python, ~~70~~ 64 bytes

```
lambda x:sum(int(b'"v4!g2euqc1U'.hex()[ord(c)%26])-4for c in x)

```

Attempt This Online!

-6 bytes thanks to @loopy walt and @Steffan

# Answer
> 4 votes
# Python 3, ~~154~~ 150 bytes

-4 thanks to Ismael

```
o=0
for I in input():
    if I in'eato':o-=3
    if I in'insh':o-=2
    if I in'rdlc':o-=1
    if I in'wfgy':o+=1
    if I in'kvbp':o+=2
    if I in'jqxz':o+=3
print(o)

```

Attempt This Online!

# Answer
> 4 votes
# JavaScript (Node.js), 64 bytes

```
s=>Buffer(s).map(c=>s="11652310562103546460522044"[c%26]-4-~s)|s

```

Try it online!

# Answer
> 4 votes
# TI-Basic, 55 bytes

```
sum(seq(int(~inString("KVBPWFGYMMUURDLCINSHEATO",sub(Ans,I,1))/4)+3,I,length(Ans

```

Takes input in `Ans` as a string with all uppercase letters. `~` represents the negative symbol.

# Answer
> 4 votes
# Charcoal, 29 bytes

```
ＩΣＥＳ⊖⊖÷⌕”&⌈∨v_≕º↖Rb)}ζ⎇K⮌9”ι⁴

```

Try it online! Link is to verbose version of code. Explanation: Port of @loopywalt's answer, but only because I didn't have time to write this answer 10 hours ago. Explanation:

```
   Ｓ            Input string
  Ｅ             Map over characters
       ⌕        Find index of
             ι  Current character in
        ”...”   Compressed string `inshrdlcmumuwfgykvbpjqxz`
      ÷         Integer divide by
              ⁴ Literal integer `4`
     ⊖          Decremented
    ⊖           Decremented
 Σ              Take the sum
Ｉ               Cast to string
                Implicitly print

```

# Answer
> 4 votes
# Ruby, ~~64 ...~~ 52 bytes

```
->s{s.bytes.sum{0x69a560ad416ae264095[_1%49*3,3]-3}}

```

Attempt This Online!

Thanks south for -2 bytes. So long, TIO, and thanks for all the fish.

### How?

The value of each letter is encoded in 3 bit (0 to 6 instead of -3 to +3), then packed into a 26-digit octal number. The letter 'a' is discarded because "out of range" is automatically translated to zero, which becomes -3. This gives a 75-bit value (25\*3) which can be encoded in 19 hexadecimal nibbles.

# Answer
> 3 votes
# Retina 0.8.2, ~~88~~ 87 bytes

```
+T`eiran\dts\l\o\hc`321o
\d
$*-
+T`jk\wqvfxbgz\py`321o
\d
$*
m|u

+`.\b.

^(-)?.*
$1$.&

```

Try it online! Link includes test cases. Explanation:

```
+T`eiran\dts\l\o\hc`321o

```

Translate common letters to digits. (Some letters have special meanings, such as `o`, which means copy the other pattern, so they have to be quoted.)

```
\d
$*-

```

Expand the digits to `-`s.

```
+T`jk\wqvfxbgz\py`321o

```

Translate rare letters to digits.

```
\d
$*

```

Expand the digits to `1`s (golfier than `+`s).

```
m|u

```

Delete any leftover `m`s and `u`s.

```
+`.\b.

```

Cancel out pairs of `-`s and `1`s. This works because they create a word boundary between them.

```
^(-)?.*
$1$.&

```

Convert to decimal.

Edit: Saved 1 byte by copying @MartinEnder's code to subtract signed numbers from his answer to Add two numbers.

# Answer
> 3 votes
# C (gcc), ~~68~~ 63 bytes

-4 bytes thanks to c--

```
f(int*s){s=*s?"22763421673214657571633155"[*s%26]-52+f(s+1):0;}

```

Try it online!

---

# C (gcc), 62 bytes

With the unprintable characters from Kevin Cruijssen's answer as suggested by c-- and Mukundan314.

```
f(int*s){s=*s?""[*s-97]-4+f(s+1):0;}

```

Try it online!

# Answer
> 3 votes
# Zsh `--extendedglob`, 68 bytes

```
a=(insh rdlc um wfgy kvbp jqxz)
<<<$[${1//(#m)?/+$a[(I)*$MATCH*]-3}]

```

Try it online!

Because shell raw strings don't need quotes, using an array is shorter than doing math on a single string lookup.

```
a=(insh rdlc um wfgy kvbp jqxz)      # lookup table, offset by 3, with no 'eato'
<<<$[${1//(#m)?/+$a[(I)*$MATCH*]-3}]
#    ${1//(#m)?/                  }  # Replace every character in the string with
#               +               -3   # "+", "-3" literal strings
#                $a[(I)*$MATCH*]     # The lowest index of $a matching *<char>*, 1-indexed
                                     # If no match (e.g.: *e*) substitute "0"
#  $[                              ] # Evaluate arithmetically

```

# Answer
> 2 votes
# APL, 60 bytes

```
{s←⍵⋄+/⊃(4-⍨⍳7)+.×{s∊⍵}¨↓7 4⍴'eatoinshrdlcumumwfgykvbpjqxz'}

```

Try it online!

# Answer
> 1 votes
# Raku, 64 bytes

```
.comb>>.&{('inshrdlcmumuwfgykvbpjqxz'.index($_)//-2)div 4-2}.sum

```

Try it online!

# Answer
> 1 votes
# Pyth, 22 (or 29?) bytes.

```
sXQG-L3jC"ÅŽ˜–Žê"7
```

Test suite

*Note: the program uses characters not properly displayed by StackExchange, which have been replaced in the above snippet for readability. The link provides a correct and copyable source.*

If Pyth's supposed SBCS works the way `C` seems to imply, then this is encoded as 22 bytes. In UTF-8, it's 29 bytes. I've never found a foolproof answer to this issue.

(For the record, `C` just uses `chr` and `ord` over base 256, which would suggest each of the characters those functions spit out for range \[0-255\] should be considered a single byte. I dunno though.)

##### Explanation:

```
sXQG-L3jC"..."7 | Full code (with string contents omitted)
----------------+----------------------------------------------------------------------
        C"..."  | Convert a magic string to an integer from base 256
       j      7 | Convert this int to base 7 as a list
    -L3         | Replace each digit d with 3-d
 XQG            | Translate the input from the lowercase alphabet to the resulting list
s               | Sum the results

```

# Answer
> 0 votes
# Javascript (Browser) 155 Bytes

```
var r=s=>[...s].reduce((o,I)=>o+(({e:-3,a:-3,t:-3,o:-3,i:-2,n:-2,s:-2,h:-2,r:-1,d:-1,l:-1,c:-1,w:1,f:1,g:1,y:1,k:2,v:2,b:2,p:2,j:3,q:3,x:3,z:3})[I]||0),0);

```

# Answer
> 0 votes
# jq, ~~91~~ 86 bytes

***-5 bytes** from using `/` instead of `split()`*

```
./""|map([inside(["eato","insh","rdlc","um","wfgy","kvbp"][])]|(index(true)//6)-3)|add

```

~~Try it online!~~ Try it online!

Leaves off `jqxz` from the array, and instead uses `//6` to catch those cases.

---
Tags: code-golf, string
---


title: Zip ragged lists

text:
# Question
Title: Zip ragged lists
In Haskell (and probably some other languages or something) `zip` is a function which takes two lists, and produces a list of tuples by pairing elements at the same index:

```
zip [1,2,3] [6,5,4] = [(1,6),(2,5),(3,4)]

```

If there are extra elements on one of the input lists those are trimmed off and don't appear in the result:

```
zip [1,2,3] [6,5,4,3,2,1] = [(1,6),(2,5),(3,4)]

```

A ragged list is like a list, but instead of just containing one type of thing it can contain two types of things, one being itself. For example:

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

```

This is a ragged list of integers. It contains integers and ragged lists of integers.

You can easily imagine zipping ragged lists which have a similar enough structure. For example:

```
zip [1,[2,3,9],3] [2,[3,4,5,6]] = [(1,2),[(2,3),(3,4),(9,5)]]

```

But things get a little tricky when you have to combine an element (e.g. an integer) with a structure (e.g. a ragged list of integers). To do this we are going to *distribute* the element across the structure. Some examples:

```
zip [1] [[2,3,[5,4]]] = [[(1,2),(1,3),[(1,5),(1,4)]]]
zip [1,2] [3,[4,5]] = [(1,3),[(2,4),(2,5)]]
zip [[2,3],4] [1,[6,7]] = [[(2,1),(3,1)],[(4,6),(4,7)]]

```

This whole behavior can be captured by this Haskell program:

```
data Ragged a
  = Ragged (Either a [Ragged a])

zip' :: Ragged a -> Ragged b -> Ragged (a, b)
zip' (Ragged x) (Ragged y) = Ragged $ go x y
  where
    go :: Either a [Ragged a] -> Either b [Ragged b] -> Either (a,b) [Ragged (a,b)]
    go (Left x) (Left y) =
      Left (x, y)
    go (Left x) (Right ys) =
      Right $ (zip' $ Ragged $ Left x) <$> ys
    go (Right xs) (Left y) =
      Right $ (flip zip' $ Ragged $ Left y) <$> xs
    go (Right xs) (Right ys) =
      Right $ zipWith zip' xs ys

```

Attempt This Online!

## Task

Take as input two ragged lists of positive integers and output their `zip` as defined above. The output should be a ragged list of integer tuples. You may represent ragged lists and tuples in any reasonable way. The definition of ragged lists given here implies there is always a list at the top level, (e.g. `1` is not a ragged list of integers) so you may assume that this is the case for your inputs, but you may also support integers at the top level if its more convenient.

This is so the goal is to minimize the size of your source code as measured in bytes.

# Answer
# Whython, 53 bytes

```
z=lambda a,b:map(z,[+a]*len(b)?a,[+b]*len(a)?b)?(a,b)

```

Takes two lists; returns `map` iterators instead of lists. Attempt This Online!

### Explanation

Partly inspired by 97.100.97.109's Python answer.

```
z=lambda a,b:

```

Define `z` as a function of two arguments `a` and `b`.

```
map(z,...,...)

```

Map `z` over corresponding items from the following two iterables:

```
[+a]*len(b)?a

```

If `a` is an integer and `b` is a list, convert `a` to a list by putting it into a single-element list and then repeating it a number of times equal to the length of `b`. Otherwise, the first expression errors, either because `+a` is an error when `a` is a list, or because `len(b)` is an error when `b` is an int. In this case, catch the error with `?` and use just `a` instead.

```
[+b]*len(a)?b

```

The second iterable is the same thing but for `b` instead of `a`.

If either or both of `a` and `b` are lists, the `map` will get two lists as arguments and will succeed. However, if they are both ints, the `map` will get two ints as arguments and will error. Thus:

```
?(a,b)

```

If the `map` errors, return a tuple containing `a` and `b` instead.
> 6 votes

# Answer
# Haskell, ~~100~~ 92 bytes

```
data R a=I a|L[R a]
I a%I b=I(a,b)
L x%L y=L$zipWith(%)x y
a%L y=L$map(a%)y
L x%b=L$map(%b)x

```

Try it online!
> 4 votes

# Answer
# JavaScript, 76 bytes

```
z=(a,b,f=c=>c.shift?.()??c)=>a<z|b<z?[]:a+b>z?[z(f(a),f(b)),...z(a,b)]:[a,b]

```

```
z=(a,b,f=c=>c.shift?.()??c)=>a<z|b<z?[]:a+b>z?[z(f(a),f(b)),...z(a,b)]:[a,b]

console.log(JSON.stringify(z([1,2,3], [6,5,4]))); // [(1,6),(2,5),(3,4)]
console.log(JSON.stringify(z([1,2,3], [6,5,4,3,2,1]))); // [(1,6),(2,5),(3,4)]
console.log(JSON.stringify(z([1,[2,3,9],3], [2,[3,4,5,6]]))); // [(1,2),[(2,3),(3,4),(9,5)]]
console.log(JSON.stringify(z([1], [[2,3,[5,4]]]))); // [[(1,2),(1,3),[(1,5),(1,4)]]]
console.log(JSON.stringify(z([1,2], [3,[4,5]]))); // [(1,3),[(2,4),(2,5)]]
console.log(JSON.stringify(z([[2,3],4], [1,[6,7]]))); // [[(2,1),(3,1)],[(4,6),(4,7)]]
```

Code with comment:

```
zip = (a, b) => {
  if (isEmptyArray(a) || isEmptyArray(b)) return [];
  if (isNonEmptyArray(a) || isNonEmptyArray(b)) {
    return [zip(pop(a), pop(b)), ...zip(a, b)];
  }
  return [a, b];
};
isEmptyArray = a => a < zip;
isNonEmptyArray = a => a > zip;
pop = a => Array.isArray(a) ? a.shift() : a;

```
> 2 votes

# Answer
# K (ngn/k), 58 bytes

```
{$[&/i:`i=@:'(x;y);x,'y;|/i;x o'y;o'/#/:/|1(&/#:')\(x;y)]}

```

Try it online!
> 2 votes

# Answer
# Python, ~~101~~ 91 bytes

*-10 bytes thanks to @DLosc*

```
g=lambda a,b:(a,b)*(a*0==0==b*0)or map(g,a*0!=0and a or[a]*len(b),b*0!=0and b or[b]*len(a))

```

Attempt This Online!

Takes in input as a tuple.

# Python, ~~97~~ 87 bytes

```
g=lambda a,b:(a,b)*(a*0==0==b*0)or map(g,a*(a*0!=0)or[a]*len(b),b*(b*0!=0)or[b]*len(a))

```

Attempt This Online!

Same as above, except it also assumes that the integers are never zero.
> 1 votes

# Answer
# JavaScript, 90 bytes

Expects input like `z(list1, list2)`. Supports integer inputs

```
z=(a,b)=>a>z?a.flatMap((x,i)=>b[i]?[z(x,b[i])]:b>z?[]:[z(x,b)]):b>z?b.map(x=>z(a,x)):[a,b]

```

**Ungolfed version**:

```
z=(a,b)=>{
  if (a>z) return a.flatMap((x,i)=>b[i]?[z(x,b[i])]:b>z?[]:[z(x,b)])
  if (b>z) return b.map(x=>z(a,x))

  return [a,b]
}

```

Try it:

```
z=(a,b)=>a>z?a.flatMap((x,i)=>b[i]?[z(x,b[i])]:b>z?[]:[z(x,b)]):b>z?b.map(x=>z(a,x)):[a,b]

;[
  [
    [1, 2], '[1,2]'
  ],
  [
    [1, [2,3]], '[[1,2],[1,3]]'
  ],
  [
    [1, [2,[3]]], '[[1,2],[[1,3]]]'
  ],
  [
    [[2,3], 1], '[[2,1],[3,1]]'
  ],
  [
    [[1,2,3], [4,5,6]], '[[1,4],[2,5],[3,6]]'
  ],
  [
    [[1,2], [4,5,6]], '[[1,4],[2,5]]'
  ],
  [
    [[1,2,3], [4,5]], '[[1,4],[2,5]]'
  ],
  [
    [[1], [[2,3,[4,5]]]], '[[[1,2],[1,3],[[1,4],[1,5]]]]'
  ],
  [
    [[1,2], [3,[4,5]]], '[[1,3],[[2,4],[2,5]]]'
  ],
  [
    [[[1,2],3], [4,[5,6]]], '[[[1,4],[2,4]],[[3,5],[3,6]]]'
  ],
].forEach(([[a,b],c])=>console.log(JSON.stringify(z(a,b)), JSON.stringify(z(a,b)) === c))
```

## UPD 126 -\> 98

Thanks to tsh for the tip to reduce bytes count
> 1 votes

# Answer
# Rust, ~~294~~ ~~284~~ 271 bytes

```
#[derive(Clone)]
enum A{b(i32),c(Vec<A>)}fn f(x:(A,A))->A{A::c(match x{(A::c(i),A::c(j))=>i.into_iter().zip(j).map(f).collect(),(y,A::c(j))=>j.into_iter().map(|k|f((y.clone(),k))).collect(),(A::c(i),z)=>i.into_iter().map(|k|f((k,z.clone()))).collect(),w=>vec![w.0,w.1]})}

```

Playground Link
> 1 votes

# Answer
# Charcoal, 63 bytes

```
⊞υθＦυＦ⊙ι⁼κ⁺κ⟦⟧«≔⮌Ｅ²⊟ιηＵＭη⎇⁼λ⁺λ⟦⟧λＥ§η¬μλＦＥ⌊ＥηＬλＥη§νλ«⊞ιλ⊞υλ»»⭆¹θ

```

Try it online! Link is to verbose version of code. Takes input as a pair list of ragged lists, and outputs using pair lists as tuples. Explanation:

```
⊞υθＦυ

```

Start a breadth-first search with the pair of input lists.

```
Ｆ⊙ι⁼κ⁺κ⟦⟧«

```

If at least one corresponding entry from the pair is a list, then:

```
≔⮌Ｅ²⊟ιη

```

Extract the pair into a new list so that they can be replaced by their zipped entries.

```
ＵＭη⎇⁼λ⁺λ⟦⟧λＥ§η¬μλ

```

If one of the entries is an integer then repeat it for the length of the other list.

```
ＦＥ⌊ＥηＬλＥη§νλ«

```

Loop over the transpose of the entries.

```
⊞ιλ⊞υλ

```

Push the new pairs back to the list that held the pair being processed but also to the list of lists to be processed so that they will themselves be zipped.

```
»»⭆¹θ

```

Pretty-print the final list because the default output format doesn't work well for ragged lists.
> 1 votes

# Answer
# Elm, ~~159~~ 155 bytes

*4 bytes saved thanks to Wheat Wizard!*

```
type R a=I a|L(List(R a))
z v u=case(v,u)of
 (I x,I y)->I(x,y)
 (L x,L y)->L(List.map2 z x y)
 (_,L y)->L(List.map(z v)y)
 (L x,_)->L(List.map(\n->z n u)x)

```

Elm's pattern matching is not very golfy, and given the nature of the language, it is hard to squeeze out bytes in the case branches themselves. We define a recursive type `R` to encapsulate the ragged structures used in the challenge, since Elm does not natively support ragged lists. The function itself `z` is called on two such structures (of `Int`s), and returns a structure (of pairs of ints `(Int, Int)`). We must also fully qualify such structures to pass it to the program, as is the nature of Elm:

```
z
  (L[I 1, L[I 2, I 3, I 9], I 3])
  (L[I 2, L[I 3, I 4, I 5, I 6]])

```

corresponds to `zipRagged [1,[2,3,9],3] [2,[3,4,5,6]]`. In the testing harness below, I've defined a `parseCase` function which allows the function to be called as `z (parseCase "[1,[2,3,9],3]") (parseCase "[2,[3,4,5,6]]")`.

## Testing

You can try it here with the following test program:

```
import Html exposing (..)

-- begin code golf
type R a=I a|L(List(R a))
z v u=case(v,u)of
 (I x,I y)->I(x,y)
 (L x,L y)->L(List.map2 z x y)
 (_,L y)->L(List.map(z v)y)
 (L x,_)->L(List.map(\n->z n u)x)
-- end code golf
-- z : R Int -> R Int -> R (Int, Int)

-- display
showResult : R (Int, Int) -> String
showResult res =
  case res of
    I (x, y) -> "(" ++ (String.fromInt x) ++ "," ++ (String.fromInt y) ++ ")"
    L list -> "[" ++ (List.map showResult list |> String.join ", ") ++ "]"

-- zip [1,[2,3,9],3] [2,[3,4,5,6]] = [(1,2),[(2,3),(3,4),(9,5)]]

parseCase : String -> R Int
parseCase str = str |> String.split "" |> parseCaseHelper

type alias ParseState =
  { depth : Int
  , build : R Int
  , number : String
  , stack : List (R Int)
  }
pushNumber : ParseState -> ParseState
pushNumber state =
  if state.number == "" then state
  else
    let
      parsedNumber = state.number
        |> String.toInt
        |> Maybe.withDefault -1
      pushed = case state.build of
        I x -> I parsedNumber
        L v -> L (v ++ [I parsedNumber])
    in
      { state
      | number = ""
      , build = pushed }

parseCaseHelper : List (String) -> R Int
parseCaseHelper =
  List.foldl
    (\el state ->
      if el == "[" then
        { state
        | stack = state.build :: state.stack
        , build = L []
        }
      else if el == "," then
        pushNumber state
      else if el == "]" then
        let nextState = pushNumber state
        in
          case nextState.stack of
            head :: rest ->
              { nextState
              | stack = rest
              , build = case (nextState.build, head) of
                (L b, L h) -> L (h ++ [nextState.build])
                _ -> L [I -2] -- never occurs. "error"
              }
            _ -> state -- unbalanced. "error"
      else if "0" <= el && el <= "9" then
        { state | number = state.number ++ el }
      else state
    )
    { depth = 0, build = L [], number = "", stack = [] }
  >> .build
  >> (\x -> case x of
    L ((L inner) :: rest) -> L inner
    _ -> x
  )

cases =
  [
    ( "[1,[2,3,9],3]"
    , "[2,[3,4,5,6]]"
    )
  ,
    ( "[1]"
    , "[[2,3,[5,4]]]"
    )
  ,
    ( "[1,2]"
    , "[3,[4,5]]"
    )
  ,
    ( "[[2,3],4]"
    , "[1,[6,7]]"
    )
  ]

overTuple : (a -> b -> c) -> (a, b) -> c
overTuple fn (left, right) = fn left right

main = cases
  |> List.map
    (Tuple.mapBoth parseCase parseCase >> overTuple z >> showResult)
  |> List.map (\str -> Html.p [] [ text str ] )
  |> Html.div []

```
> 1 votes

---
Tags: code-golf, ragged-list
---