26
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ Sandbox (deleted) \$\endgroup\$
    – Stephen
    Commented May 31, 2017 at 20:50
  • \$\begingroup\$ Would it be acceptable to take n as a code-point? (for esoteric languages such as brain-flak) \$\endgroup\$
    – DJMcMayhem
    Commented May 31, 2017 at 21:29
  • \$\begingroup\$ @DJMcMayhem sure. \$\endgroup\$
    – Stephen
    Commented May 31, 2017 at 21:30

45 Answers 45

15
\$\begingroup\$

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]
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Nice use of ~, would never have though of that for this. \$\endgroup\$
    – Stephen
    Commented May 31, 2017 at 21:19
11
\$\begingroup\$

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 Ɠ

\$\endgroup\$
3
  • \$\begingroup\$ Failed 4 byte solution from original version of post: ịµU= \$\endgroup\$ Commented May 31, 2017 at 21:59
  • \$\begingroup\$ 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. \$\endgroup\$
    – user62131
    Commented May 31, 2017 at 22:21
  • \$\begingroup\$ @ais512 Good idea, I have actually never used the input before in an answer because implicit arguments tend to be more efficient. \$\endgroup\$ Commented May 31, 2017 at 22:29
10
\$\begingroup\$

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 
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Very clever approach! \$\endgroup\$
    – Luis Mendo
    Commented May 31, 2017 at 21:21
  • 3
    \$\begingroup\$ @LuisMendo Thankyou! That is quiet the complement coming from you :) \$\endgroup\$
    – DJMcMayhem
    Commented May 31, 2017 at 21:25
  • \$\begingroup\$ Now we see if Jelly can beat this xD \$\endgroup\$
    – Stephen
    Commented May 31, 2017 at 21:26
6
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

Python, 24 22 bytes

-2 bytes thanks to Adnan.

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

Try it online!

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

05AB1E, 7 5 bytes

-2 bytes thanks to Adnan

ÂøsèË

Try it online! or Try all tests

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

Try it online!

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

Haskell, 22 bytes

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

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

Try it online!

\$\endgroup\$
5
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ @MartinEnder Jabberwocky? \$\endgroup\$
    – Stephen
    Commented Jun 1, 2017 at 2:33
  • 3
    \$\begingroup\$ @StephenS Jabberwocky. \$\endgroup\$ Commented Jun 1, 2017 at 12:30
  • \$\begingroup\$ @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. \$\endgroup\$ Commented Jun 1, 2017 at 12:31
  • \$\begingroup\$ @MartinEnder I kind of knew that, but it wasn't important enough to ping you. Thanks for the confirmation and the link :) \$\endgroup\$
    – Stephen
    Commented Jun 1, 2017 at 12:40
4
\$\begingroup\$

Java 8, 43 42 bytes

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

Try it here.

\$\endgroup\$
4
\$\begingroup\$

Cubix, 22 bytes

[email protected]):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.

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ 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! \$\endgroup\$
    – nmjcman101
    Commented Jun 1, 2017 at 13:25
  • 1
    \$\begingroup\$ @nmjcman101 Turns out it can be much shorter than that using newer features. \$\endgroup\$
    – DJMcMayhem
    Commented Oct 31, 2017 at 16:48
  • \$\begingroup\$ Oh wow I'm out of practice, I can barely even read V anymore \$\endgroup\$
    – nmjcman101
    Commented Oct 31, 2017 at 16:53
  • \$\begingroup\$ @nmjcman101 I've posted an explanation (and golfed a little more) \$\endgroup\$
    – DJMcMayhem
    Commented Oct 31, 2017 at 17:04
3
\$\begingroup\$

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>>.

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

CJam, 8 bytes

l~_W%.==

Try it online!

0-indexed index goes first.

\$\endgroup\$
3
\$\begingroup\$

R 51 bytes

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

Anonymous function, uses 1-based indexing

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 43 bytes: function(s,n)(s=utf8ToInt(s))[n]==rev(s)[n] \$\endgroup\$
    – Giuseppe
    Commented Oct 31, 2017 at 16:02
3
\$\begingroup\$

Ruby, 22 20 18 bytes

->s,n{s[n]==s[~n]}
\$\endgroup\$
2
  • 4
    \$\begingroup\$ I guess ->s,n{s[n]==s[~n]} should work? (Got no idea of ruby) \$\endgroup\$
    – Christoph
    Commented Jun 1, 2017 at 13:04
  • \$\begingroup\$ It does, nice! Thanks! \$\endgroup\$ Commented Jun 1, 2017 at 15:53
3
\$\begingroup\$

Clojure, 27 bytes

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

Wow, this was shorter than I expected.

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ " 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. \$\endgroup\$
    – Jonah
    Commented Oct 31, 2017 at 14:28
  • \$\begingroup\$ @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. \$\endgroup\$
    – J. Sallé
    Commented Oct 31, 2017 at 14:30
  • \$\begingroup\$ 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. \$\endgroup\$
    – Adám
    Commented Oct 31, 2017 at 16:04
  • \$\begingroup\$ @Adám I thought that happened because, when called monadically, takes the first element of the argument? Anyway, I'll edit to clarify. \$\endgroup\$
    – J. Sallé
    Commented Oct 31, 2017 at 16:06
3
\$\begingroup\$

C# (Visual C# Interactive Compiler), 20 bytes

I don't have enough reputation to comment on TheLethalCoder's answer, but in C# 8 you can save some more bytes.

s=>n=>s[n]==s[^++n];

Try it online!

\$\endgroup\$
3
\$\begingroup\$

J, 6 5 bytes

{]=|.

Try it online!

-4 bytes thanks to FrownyFrog for {(=|.)

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!

original answer (10 bytes)

{=/@(,:|.)

,:|. 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!

\$\endgroup\$
0
2
\$\begingroup\$

Mathematica, 34 Bytes

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

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)

    ]
}
\$\endgroup\$
2
\$\begingroup\$

PHP>=7.1, 36 Bytes

[,$t,$p]=$argv;echo$t[$p]==$t[~+$p];

Online Version

\$\endgroup\$
1
  • 1
    \$\begingroup\$ ~+$p saves one byte. \$\endgroup\$
    – user63956
    Commented Jun 1, 2017 at 4:12
2
\$\begingroup\$

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!

\$\endgroup\$
2
\$\begingroup\$

Lua, 46 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ you can't assume the input is already in s, and you need to output it as well \$\endgroup\$ Commented Jun 1, 2017 at 10:56
2
\$\begingroup\$

C, 36 35 bytes

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

Uses 0-based indexing, naturally.

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ I think -1-n can be +~n. \$\endgroup\$ Commented Oct 31, 2017 at 16:10
2
\$\begingroup\$

Factor, 24 bytes

[ 2dup nth -rot nth* = ]

Try it online!

Explanation

nth* is like nth except it indexes from the back; if 0 nth is the first element, 0 nth* is the last.

             ! 1 "[][]"
2dup         ! 1 "[][]" 1 "[][]"
nth          ! 1 "[][]" 93
-rot         ! 93 1 "[][]"
nth*         ! 93 91
=            ! f
\$\endgroup\$
2
\$\begingroup\$

Thunno, \$ 8 \log_{256}(96) \approx \$ 6.58 bytes

Drz.=sAI

Attempt This Online!

0-indexed. Change AI to AH if you want it to be 1-indexed.

Explanation

Drz.=sAI  # Implicit input
Dr        # Duplicate and reverse
  z.=     # Zipped equality
     sAI  # Swap and index in
          # Implicit output
\$\endgroup\$
2
\$\begingroup\$

Vyxal, 4 bytes

fḂ=i

Try it Online!

Explanation

fḂ=i  # Implicit input
f     # Flatten into a list of characters
 Ḃ    # Bifurcate: duplicate and reverse
  =   # Are they equal (vectorises)
   i  # Index in
      # Implicit output
\$\endgroup\$
2
\$\begingroup\$

ZSH, 32

f(){read s n;[ $s[n] = $s[-n] ]}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Japt, 10 9 8 bytes

gV ¥Ug~V

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.