# Does the nth char equal the nth from last char?

Inspired by Does the start equal the end

Given a string s and an integer n, output a truthy/falsey as to whether the nth char in s equals the nth from the end char in s.

# Input

A non-empty string and an integer. You can use 0-based indexing or 1-based indexing. The integer is guaranteed to be valid based on the string. For example, if the string is "supercalifragalistic123", the integer can be from 1 to 23 for 1-based indexing, and 0 to 22 for 0-based indexing. Please note that n can be larger than half the length of s.

Input is limited to printable ASCII.

# Output

A truthy/falsey value based on whether the nth value in s equals the nth from last value in s.

Please note that the last char is in position 0 for 0-based indexing and position 1 for 1-based indexing. Think of it as comparing the string to its reverse.

# Test Cases

0-indexed

"1", 0         Truthy 1 == 1
"abc", 1       Truthy b == b
"aaaaaaa", 3   Truthy a == a
"[][]", 1      Falsey ] != [
"[][]", 0      Falsey [ != ]
"ppqqpq", 2    Truthy q == q
"ababab", 5    Falsey a != b
"12345", 0     Falsey 1 != 5
"letter", 1    Truthy e == e
"zxywv", 3     Falsey w != x


1-indexed

"1", 1         Truthy 1 == 1
"abc", 2       Truthy b == b
"aaaaaaa", 4   Truthy a == a
"[][]", 2      Falsey ] != [
"[][]", 1      Falsey [ != ]
"ppqqpq", 3    Truthy q == q
"ababab", 6    Falsey a != b
"12345", 1     Falsey 1 != 5
"letter", 2    Truthy e == e
"zxywv", 4     Falsey w != x

• Sandbox (deleted) – Stephen May 31 '17 at 20:50
• Would it be acceptable to take n as a code-point? (for esoteric languages such as brain-flak) – DJMcMayhem May 31 '17 at 21:29
• @DJMcMayhem sure. – Stephen May 31 '17 at 21:30

# Jelly, 5 4 bytes

=UƓị


Try it online!

There should be no shorter answers in Jelly. An program would need comparison, reversal/negation, an index call, and a byte for control flow (Ɠ in this case), which adds up to four bytes.

How it works

 =UƓị
- (implicit) input string
=     - equals (vectorizing by characters because a string is a charlist)
U    - the reversed string
ị  - get the element at the index of:
Ɠ   - the input index


-1 byte thanks to @ais523, using Ɠ

• Failed 4 byte solution from original version of post: ịµU= – CalculatorFeline May 31 '17 at 21:59
• You can improve it to four bytes by making it monadic rather than dyadic (and taking n from standard input rather than an argument): Try it online! This technique is often useful when you're wasting a byte on control flow and an additional byte on ³, as the Ɠ costs one byte but makes the ³ implicit and often gives you more control flow flexibility. – user62131 May 31 '17 at 22:21
• @ais512 Good idea, I have actually never used the input before in an answer because implicit arguments tend to be more efficient. – fireflame241 May 31 '17 at 22:29

# JavaScript (ES6), 26 bytes

s=>n=>s[n]==s.substr(~n,1)


Alternatively:

s=>n=>s[n]==s.slice(~n)[0]


This one almost works, but fails when n == 0 (because s.slice(-1,0) == ""):

s=>n=>s[n]==s.slice(~n,-n)


Another 26-byte solution that @RickHitchcock pointed out:

s=>n=>s[n]==s[s.length+~n]

• Nice use of ~, would never have though of that for this. – Stephen May 31 '17 at 21:19

# MATL, 5 bytes

tP=w)


Try it online!

Explanation:

t   % Duplicate the input

Stack:
['ppqqpq' 'ppqqpq']

P   % Reverse the top element of the stack

Stack:
['ppqqpq' 'qpqqpp']

=   % Equals. Push an array of the indices that are equal

Stack:
[[0 1 1 1 1 0]]

w   % Swap the top two elements

Stack:
[[0 1 1 1 1 0], 3]

)   % Grab the a'th element of b

• Very clever approach! – Luis Mendo May 31 '17 at 21:21
• @LuisMendo Thankyou! That is quiet the complement coming from you :) – DJMcMayhem May 31 '17 at 21:25
• Now we see if Jelly can beat this xD – Stephen May 31 '17 at 21:26

# Octave, 22 bytes

@(s,n)s(n)==s(end-n+1)


Try it online!

Or the same bytecount:

@(s,n)s(n)==flip(s)(n)


Try it online!

Explanation:

It's quite straight forward. The first one takes a string s and an integer n as inputs and checks the n'th element s(n) against the "last-n+1" element for equality.

The second one checks the n'th element s(n) against the n'th element of s reversed.

# 05AB1E, 7 5 bytes

ÂøsèË

Â     # Add a reversed copy on top of the original string
ø    # Zip
sè  # Extract the nth element
Ë # Check if they are equal


Try it online!

• ÂøsèË saves two bytes – Adnan May 31 '17 at 21:37
• @Adnan Thanks! I knew there was a 1 byte way to add a reversed copy, I just couldn't remember how it was labeled. – Riley May 31 '17 at 21:43
• @ComradeSparklePony I forgot to update it to include Adnan's suggestion. – Riley May 31 '17 at 22:08

s#n=s!!n==reverse s!!n


0-basd. Usage example: "letter" # 1 -> True.

Try it online!

# Alice, 24 bytes

/t.~e?/-mom
\I!RtI&1n;@/


Try it online!

Input consists of the string on one line, and the number on the second line. Output is Jabberwocky if the characters are the same, and nothing otherwise.

### Explanation

This program is mostly in ordinal mode, with one command in cardinal mode. Linearized, the program is as follows:

I.ReI&1m;mt!~t?&-no

I  % Input first line
% STACK: ["ppqqpq"]
.  % Duplicate top of stack
% STACK: ["ppqqpq", "ppqqpq"]
R  % Reverse top of stack
% STACK: ["ppqqpq", "qpqqpp"]
e  % Push empty string
% STACK: ["ppqqpq", "qpqqpp", ""]
I  % Input next line
% STACK: ["ppqqpq", "qpqqpp", "", "3"]
&  % (cardinal mode) Pop stack and repeat next command that many times
% STACK: ["ppqqpq", "qpqqpp", ""], ITERATOR: [3]
1  % Append "1" to top of stack
% STACK: ["ppqqpq", "qpqqpp", "111"]
m  % Truncate so the top two strings on the stack have the same length
% STACK: ["ppqqpq", "qpq", "111"]
;  % Discard top of stack
% STACK: ["ppqqpq", "qpq"]
m  % Truncate again
% STACK: ["ppq", "qpq"]
t  % Extract last character
% STACK: ["ppq", "qp", "q"]
!  % Move top of stack to tape
% STACK: ["ppq", "qp"]
~  % Swap
% STACK: ["qp", "ppq"]
t  % Extract last character
% STACK: ["qp", "pp", "q"]
?  % Copy data from tape onto top of stack
% STACK: ["qp', "pp", "q", "q"]
&  % Iterator: effectively a no-op in ordinal mode when the top of the stack is a 1-character string
% STACK: ["qp", "pp", "q"], ITERATOR: ["q"]
-  % Remove occurrences: here, result is "" iff the characters are equal
% STACK: ["qp", "pp", ""]
n  % Logical Not (for a consistent truthy value)
% STACK: ["qp", "pp", "Jabberwocky"]
o  % Output top of stack

• @MartinEnder Jabberwocky? – Stephen Jun 1 '17 at 2:33
• @StephenS Jabberwocky. – Martin Ender Jun 1 '17 at 12:30
• @StephenS Btw, I don't get notifications if you just mention me on random posts. Pings only work if the post is mine or I've commented myself (and I think if I edited the post). You're usually better off pinging me in chat. – Martin Ender Jun 1 '17 at 12:31
• @MartinEnder I kind of knew that, but it wasn't important enough to ping you. Thanks for the confirmation and the link :) – Stephen Jun 1 '17 at 12:40

# Python, 24 22 bytes

lambda s,n:s[n]==s[~n]


Try it online!

• I think you can replace -n-1 by ~n. – Adnan May 31 '17 at 21:11
• Why only Python2? Seems to work on Python3 just fine, you should change it to just 'Python'. – sagiksp Jun 1 '17 at 9:52
• @sagiksp it's the default template output in TIO – Felipe Nardi Batista Jun 1 '17 at 10:54
• Oh, makes sense. – sagiksp Jun 1 '17 at 13:43
• @sagiksp Yeah, it's the template from TIO but updated. :) – totallyhuman Jun 1 '17 at 17:03

# Cubix, 22 bytes

..@.IAp):tBvpptc?1.\O0


1-indexed, takes input as index,string, separated by a space.

Try it online

Cubified

    . .
@ .
I A p ) : t B v
p p t c ? 1 . \
O 0
. .


### Explanation

This is mostly linear. The main logic is

IAp):tBpptc

IA           Get the first input as an int and the rest as a string.
p):        Move the index to the top of the stack, increment it, and copy it.
t       Look up the appropriate character in the string.
Bpp    Reverse the stack and put the index and character back on top.
t   Look up the appropriate character in the reversed string.
c  XOR the two characters.


We then branch with ? to Output 1 if the result is 0 and 0 otherwise.

# Java 8, 43 42 bytes

s->n->s.charAt(n)==s.charAt(s.length()+~n)


Try it here.

# C#, 28 27 bytes

s=>n=>s[n]==s[s.Length+~n];


Saved a byte thanks to @KevinCruijssen.

Compiles to a Func<string, Func<int, bool>>.

• You can save a byte by changing s.Length-n-1 to s.Length+~n. – Kevin Cruijssen Jun 1 '17 at 9:06
• @KevinCruijssen Thanks, nice trick never would have thought of that. – TheLethalCoder Jun 1 '17 at 9:08
• I will be completely honest, I got it from the comment of the JS answer myself. :) Byte-operations aren't really my expertise. – Kevin Cruijssen Jun 1 '17 at 9:14

# CJam, 8 bytes

l~_W%.==


Try it online!

0-indexed index goes first.

## R 51 bytes

function(s,n){s=el(strsplit(s,''));s[n]==rev(s)[n]}


Anonymous function, uses 1-based indexing

• 43 bytes: function(s,n)(s=utf8ToInt(s))[n]==rev(s)[n] – Giuseppe Oct 31 '17 at 16:02

## Ruby, 22 20 18 bytes

->s,n{s[n]==s[~n]}

• I guess ->s,n{s[n]==s[~n]} should work? (Got no idea of ruby) – Christoph Jun 1 '17 at 13:04
• It does, nice! Thanks! – reitermarkus Jun 1 '17 at 15:53

## Clojure, 27 bytes

#(nth(map =(reverse %)%)%2)


Wow, this was shorter than I expected.

# APL (Dyalog), 10 5 bytes

⊃=⊃∘⌽


This is a tacit function, which needs to be assigned a name such as f←⊃=⊃∘⌽, and then called as int f string.

Thanks to @Adám for a whopping 5 bytes.

### How it works:

⊃=⊃∘⌽  ⍝ Main function; tacit.
⍝ Inputs are ⍺ = 1 (left) and ⍵ = 'abca' (right).
⊃      ⍝ ⍺⊃⍵, meaning 'pick the ⍺-th element of ⍵'
=     ⍝ Compare to
⌽  ⍝ ⌽⍵, meaning 'invert ⍵'
⊃    ⍝ Again, ⍺⊃⍵, but:
∘   ⍝ Compose. This turns ⌽ into the right argument for ⊃,
⍝ which becomes 'pick the ⍺-th element from ⌽(the inverse of)⍵'


Try it online!

The 22 byte answer was edited out. If you want to see it, check the revision history.

• " it takes the input in a non conventional way" -- taking 2 element input as the left and right args in APL is completely standard and always acceptable unless the OP specifically forbids it for some bizarre reason. – Jonah Oct 31 '17 at 14:28
• @Jonah yeah, people in chat enlightened me about that. I left it as is because OP doesn't specify clearly if it's okay or not. I'll edit that when I get back to my PC so the shorter answer appears first. – J. Sallé Oct 31 '17 at 14:30
• Regarding "implicitly assumes": Actually, this function will work even when called monadically, and will then appear to use 1 as default left argument. Try it online! The functions don't assume anything; they are being applied dyadically because they are given both a left and a right argument. – Adám Oct 31 '17 at 16:04
• @Adám I thought that happened because, when called monadically, ⊃ takes the first element of the argument? Anyway, I'll edit to clarify. – J. Sallé Oct 31 '17 at 16:06

# V, 26, 16, 13 bytes

ä$Àñã2xñVpøˆ±  Try it online! Hexdump: 00000000: e424 c0f1 e332 78f1 5670 f888 b1 .$...2x.Vp...


1 indexed.

Explanation:

ä$" Duplicate this line horizontally Àñ ñ " Arg1 times... ã " Move to the center of this line 2x " And delete two characters V " Select this whole line p " And replace it with the last pair of characters we deleted ø " Count the number of matches of the following regex... <0x88> " Any character ± " Followed by itself  For reference, my original answer was: Àñx$x|ñxv$hhpÓ¨.©±/1 ñllS0  Try it online! (0 indexed) Hexdump: 00000000: c0f1 7824 787c f178 7624 6868 70d3 a82e ..x$x|.xv$hhp... 00000010: a9b1 2f31 0af1 6c6c 5330 ../1..llS0  • Try it online! This is a bit shorter. Man the Àñx$x|ñ feels like too many characters. I tried a regex only, but it ended up being like 24 long! – nmjcman101 Jun 1 '17 at 13:25
• @nmjcman101 Turns out it can be much shorter than that using newer features. – DJMcMayhem Oct 31 '17 at 16:48
• Oh wow I'm out of practice, I can barely even read V anymore – nmjcman101 Oct 31 '17 at 16:53
• @nmjcman101 I've posted an explanation (and golfed a little more) – DJMcMayhem Oct 31 '17 at 17:04

# Mathematica, 34 Bytes

s=StringTake;s[#,{#2}]==s[#,{-#2}]&

• StringTake[#, #2] takes the first #2 characters of #. StringPart would work well in this case. #~(s=StringPart)~-#2==s@##& – JungHwan Min May 31 '17 at 23:30
• my wrong. fixed! – ZaMoC May 31 '17 at 23:33
• #~s~{#2}==#~s~{#2}& would always yield True... – JungHwan Min May 31 '17 at 23:34
• final fixed!.... – ZaMoC May 31 '17 at 23:36
• Actually, you can take a List of Strings as input, so #[[#2]]==#[[-#2]]& would suffice – JungHwan Min May 31 '17 at 23:39

# Perl 6, 27 bytes

{[eq] $^a.comb[$^b,*-1-$b]}  Test it { # bare block lambda with two placeholder parameters ｢$a｣ and ｢$b｣ [eq] # reduce using string equality operator$^a       # declare first positional parameter

.comb\    # split that into individual characters

[         # index into that sequence

$^b, # declare and use second parameter *-1-$b  # closure that subtracts one and the
# second parameter of the outer block
# (｢*｣ is the parameter of this closure)

]
}


# PHP>=7.1, 36 Bytes

[,$t,$p]=$argv;echo$t[$p]==$t[~+$p];  Online Version • ~+$p saves one byte. – user63956 Jun 1 '17 at 4:12

# Pyth, 8 7 bytes

q@zQ@_z


With the input reversed: first the index, then the string. It is 0-indexed.

# Explanations:

q@zQ@_z
@zQ        Get the nth (Qth) character
_z     Reverse the string
@       Get the nth character of the reversed string. Implicit input of the index
q           Test equality


Try it online!

# Lua, 46 bytes

function f(s,n)return s:byte(n)==s:byte(-n)end


Try it online!

• you can't assume the input is already in s, and you need to output it as well – Felipe Nardi Batista Jun 1 '17 at 10:56

# J, 6 bytes

-4 bytes thanks to FrownyFrog

{(=|.)


See original answer explanation -- idea is similar enough, but this is accomplished with a dyadic hook whose right verb is itself a monadic hook.

Try it online!

{=/@(,:|.)


,:|. right arg on top of reverse right arg

=/ are they elementwise equal?

{ take from that boolean list the index indicated by the left arg

Try it online!

# C, 36 35 bytes

#define f(s,n)s[n]==s[strlen(s)+~n]


Uses 0-based indexing, naturally.

Try it online!

• I think -1-n can be +~n. – Jonathan Frech Oct 31 '17 at 16:10

# Japt, 10 9 8 bytes

gV ¥Ug~V


Try it online!

## QBIC, 18 bytes

?_s;,:,1|=_sA,-a,1


Explanation

?        =     PRINT -1 if equal, 0 otherwise, between
_s     |      A substring of
;,:,1          A$string (read from cmd line), from the n'th pos, length 1 _sA,-a,1 And a substring of A$, n'th pos from the right, also 1 length
The second Substring is auto-terminated because EOF.


q~_2$=@@~==  Bad. Too much stack manipulation. ## ><> (with this interpreter), 25 bytes i:0(?v ]&=n;>~{:}[:}]&r[}  It doesn't work in TIO: the TIO interpreter doesn't reverse the new stack when doing the [ instruction, but the fish playground does — compare "abcde"5[ooooo; run here and here, for example. The string input is taken from STDIN, and we assume n is already on the stack. Uses 1-indexing. The fish gets the nth character with [:}]&, which siphons off the first n things on the stack into a new, reversed stack, manipulates that a bit, then puts the things back and saves the nth character in the register. It then reverses the whole stack and does the same again, and returns 1 if the two characters are equal, and 0 otherwise. This seems to work at TIO, for 26 bytes: i:0(?v ]&=n;>~{:}[{:}]&r[{  # C, 73 bytes Compiles as-is with GCC 6.3.1 (no flags). Some unnecessary obfuscation included. main(c,v)char**v;{c=atoi(v[2]);putchar((*++v)[c]-(*v)[strlen(*v+1)-c]);}  Usage $./a.out abcdcba 6


Truthy = nothing, falsey = garbage.

# Lua, 35 bytes

Uses 1-indexing.

s,n=...print(s:byte(n)==s:byte(-n))


Try it online!