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

35 Answers 35

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\$
  • \$\begingroup\$ Failed 4 byte solution from original version of post: ịµU= \$\endgroup\$ – CalculatorFeline May 31 '17 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 May 31 '17 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\$ – fireflame241 May 31 '17 at 22:29
14
\$\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\$
  • 3
    \$\begingroup\$ Nice use of ~, would never have though of that for this. \$\endgroup\$ – Stephen May 31 '17 at 21:19
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\$
  • 1
    \$\begingroup\$ Very clever approach! \$\endgroup\$ – Luis Mendo May 31 '17 at 21:21
  • 3
    \$\begingroup\$ @LuisMendo Thankyou! That is quiet the complement coming from you :) \$\endgroup\$ – DJMcMayhem May 31 '17 at 21:25
  • \$\begingroup\$ Now we see if Jelly can beat this xD \$\endgroup\$ – Stephen May 31 '17 at 21:26
5
\$\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\$
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\$
  • \$\begingroup\$ ÂøsèË saves two bytes \$\endgroup\$ – Adnan May 31 '17 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 May 31 '17 at 21:43
  • \$\begingroup\$ @ComradeSparklePony I forgot to update it to include Adnan's suggestion. \$\endgroup\$ – Riley May 31 '17 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\$
  • \$\begingroup\$ @MartinEnder Jabberwocky? \$\endgroup\$ – Stephen Jun 1 '17 at 2:33
  • 3
    \$\begingroup\$ @StephenS Jabberwocky. \$\endgroup\$ – Martin Ender Jun 1 '17 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\$ – Martin Ender Jun 1 '17 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 Jun 1 '17 at 12:40
5
\$\begingroup\$

Python, 24 22 bytes

-2 bytes thanks to Adnan.

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

Try it online!

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

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.

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

Java 8, 43 42 bytes

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

Try it here.

\$\endgroup\$
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\$
  • \$\begingroup\$ You can save a byte by changing s.Length-n-1 to s.Length+~n. \$\endgroup\$ – Kevin Cruijssen Jun 1 '17 at 9:06
  • \$\begingroup\$ @KevinCruijssen Thanks, nice trick never would have thought of that. \$\endgroup\$ – TheLethalCoder Jun 1 '17 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\$ – Kevin Cruijssen Jun 1 '17 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
    \$\begingroup\$ 43 bytes: function(s,n)(s=utf8ToInt(s))[n]==rev(s)[n] \$\endgroup\$ – Giuseppe Oct 31 '17 at 16:02
3
\$\begingroup\$

Ruby, 22 20 18 bytes

->s,n{s[n]==s[~n]}
\$\endgroup\$
  • 3
    \$\begingroup\$ I guess ->s,n{s[n]==s[~n]} should work? (Got no idea of ruby) \$\endgroup\$ – Christoph Jun 1 '17 at 13:04
  • \$\begingroup\$ It does, nice! Thanks! \$\endgroup\$ – reitermarkus Jun 1 '17 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\$
  • \$\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 Oct 31 '17 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é Oct 31 '17 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 Oct 31 '17 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é Oct 31 '17 at 16:06
3
\$\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\$
  • \$\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 Jun 1 '17 at 13:25
  • 1
    \$\begingroup\$ @nmjcman101 Turns out it can be much shorter than that using newer features. \$\endgroup\$ – DJMcMayhem Oct 31 '17 at 16:48
  • \$\begingroup\$ Oh wow I'm out of practice, I can barely even read V anymore \$\endgroup\$ – nmjcman101 Oct 31 '17 at 16:53
  • \$\begingroup\$ @nmjcman101 I've posted an explanation (and golfed a little more) \$\endgroup\$ – DJMcMayhem Oct 31 '17 at 17:04
2
\$\begingroup\$

Mathematica, 34 Bytes

s=StringTake;s[#,{#2}]==s[#,{-#2}]&
\$\endgroup\$
  • \$\begingroup\$ StringTake[#, #2] takes the first #2 characters of #. StringPart would work well in this case. #~(s=StringPart)~-#2==s@##& \$\endgroup\$ – JungHwan Min May 31 '17 at 23:30
  • \$\begingroup\$ my wrong. fixed! \$\endgroup\$ – J42161217 May 31 '17 at 23:33
  • \$\begingroup\$ #~s~{#2}==#~s~{#2}& would always yield True... \$\endgroup\$ – JungHwan Min May 31 '17 at 23:34
  • \$\begingroup\$ final fixed!.... \$\endgroup\$ – J42161217 May 31 '17 at 23:36
  • 1
    \$\begingroup\$ Actually, you can take a List of Strings as input, so #[[#2]]==#[[-#2]]& would suffice \$\endgroup\$ – JungHwan Min May 31 '17 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
    \$\begingroup\$ ~+$p saves one byte. \$\endgroup\$ – user63956 Jun 1 '17 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\$
  • \$\begingroup\$ you can't assume the input is already in s, and you need to output it as well \$\endgroup\$ – Felipe Nardi Batista Jun 1 '17 at 10:56
2
\$\begingroup\$

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!

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\$
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\$
  • \$\begingroup\$ I think -1-n can be +~n. \$\endgroup\$ – Jonathan Frech Oct 31 '17 at 16:10
1
\$\begingroup\$

Japt, 10 9 8 bytes

gV ¥Ug~V

Try it online!

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

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.
\$\endgroup\$
1
\$\begingroup\$

CJam, 11 bytes

q~_2$=@@~==

Bad. Too much stack manipulation.

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

><> (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[{
\$\endgroup\$
1
\$\begingroup\$

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.

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

Lua, 35 bytes

Uses 1-indexing.

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

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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