42
\$\begingroup\$

The Task

In this challenge, your task is to write a program or function which takes in a String and outputs a truthy or falsey value based on whether the first character and the last character of the input String are equal.

Input

You may take input in any way reasonable way. However, assuming that the input is present in a predefined variable is not allowed. Reading from a file, console, command line, input field etc., or taking input as a function argument is allowed.

Output

You may output in any reasonable format, except for assigning the result to a variable. Writing to a file, console, command line, modal box, function return statements etc. is allowed.

Additional Rules

  • The input can be empty String as well, for which you should return a falsey value.

  • Single-Char Input Strings should have a truthy result.

  • Your program should be case-sensitive. helloH should output a falsey value.

  • You can only have a single Truthy value and a single Falsey value. For example, outputting false for an Input String and 0 for another input String as Falsey values is not allowed.

  • Standard loopholes are not allowed.

Test Cases

Input    ->    Output

"10h01"        Truthy
"Nothing"      Falsey
"Acccca"       Falsey
"eraser"       Falsey
"erase"        Truthy
"wow!"         Falsey
"wow"          Truthy
"H"            Truthy
""             Falsey

This is , so the shortest code in bytes wins!

\$\endgroup\$
5
  • \$\begingroup\$ What characters can appear in the input? Printable ASCII? \$\endgroup\$ May 13, 2017 at 19:35
  • \$\begingroup\$ @MartinEnder Printable ASCII. Although, I don't think it matters much. \$\endgroup\$
    – Arjun
    Jun 3, 2017 at 17:29
  • \$\begingroup\$ Of course it matters. Some languages can't process non-ASCII characters or null bytes, and in a regex I can match any printable ASCII character with ., but it wouldn't match linefeeds. In general, if you find yourself using the string tag, specify exactly what characters can appear in the input. \$\endgroup\$ Jun 3, 2017 at 17:31
  • \$\begingroup\$ @MartinEnder Okay. Will take care in future. \$\endgroup\$
    – Arjun
    Jun 4, 2017 at 7:16
  • \$\begingroup\$ Suggested test case: AbAb => false \$\endgroup\$ Oct 31, 2017 at 14:40

113 Answers 113

2
\$\begingroup\$

Octave, 16 bytes

@(s)s(1)==s(end)

It takes a string s as input, and compares the first s(1) element with the last s(end).

This could be @(s)s(1)-s(end) if it was OK to swap true/false to false/true.

\$\endgroup\$
1
  • \$\begingroup\$ out of bound for empty string... \$\endgroup\$ Jul 4, 2022 at 19:36
2
\$\begingroup\$

S.I.L.O.S, 81 bytes

loadLine
a=256
c=get a
lblb
t=s
s=get a
a+1
if s b
t-c
if t d
i+1
lbld
printInt i

Try it online!

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

Common Lisp, 83 74 61 58 bytes

Original: 83 bytes

I've just started learning Common Lisp, so I feel like I'm bringing a putter to a driving range. There must be some kind of recursive macro wizardry or array manipulation possible here that I'm not seeing.

This is an anonymous function that accepts a string as its input:

(lambda (s) (let ((n (- (length s) 1))) (when (> n 0) (eq (char s 0) (char s n)))))

Prettified:

(lambda (s)
  (let ((n (- (length s) 1)))
    (when (> n 0)
      (eq (char s 0)
          (char s n)))))

Would love to see a slicker solution!

Revision 1: 74 bytes

Gotta love those standard library functions!

Ugly:

(lambda (s) (when (> (length s) 0) (eq (elt s 0) (elt (reverse s) 0))))

Pretty:

(lambda (s)
  (when (> (length s) 0)
    (eq (elt s 0)
        (elt (reverse s) 0))))

Revision 1.5: 61 bytes

Whitespace!

(lambda(s)(when(>(length s)0)(eq(elt s 0)(elt(reverse s)0))))

Revision 2: 58 bytes

Ugly:

(lambda(s)(and(>(length s)0)(not(mismatch s(reverse s)))))

Pretty:

(lambda (s)
  (and (> (length s) 0)
       (not (mismatch s (reverse s)))))

That's all for now! I think I'm smarter already.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Suggest if instead of and and (mismatch(reverse s)s) instead of (mismatch s(reverse s)) \$\endgroup\$
    – ceilingcat
    Mar 27, 2018 at 3:43
2
\$\begingroup\$

AWK, 29 34 bytes

This one might be cheating slightly, because it requires invoking AWK with the option:

`-F ''`

In GNU Awk you can use the long-form synonyms:

`--field-separator=''`

So I added 5 bytes to the total to account for this.

Ugly:

NR==1{a=$1}END{print(a==$NF)}

Pretty:

NR == 1
{
    a = $1
}

END
{
    print(a == $NF)
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I believe the rule is that you can use flags/options, but you need to include them in the byte count. \$\endgroup\$ May 14, 2017 at 4:45
  • \$\begingroup\$ With the -F '' in effect, I think this will work 1,$0=$1==$NF \$\endgroup\$
    – cnamejj
    Aug 3, 2022 at 7:31
2
\$\begingroup\$

Python, 51 bytes

s=input()
if s:print(s[0]==s[-1])
else:print(False)

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to PPCG and nice first answer! This solution can be golfed by not using if-else statements like so: Try it online! \$\endgroup\$
    – user41805
    May 14, 2017 at 9:45
2
\$\begingroup\$

Bash, 37 bytes

[ -n "$1" ]&&[ ${1:0:1} == ${1: -1} ]

Takes command line input and returns with exit status 0 (truthy) or 1 (falsy).

Test with:

bash test.sh "helloH" ; echo $?
\$\endgroup\$
1
  • \$\begingroup\$ The -n operator is the same as no operator, so you can remove it. The equality operator may be written as single =. As the substring expansion expects arithmetic expressions, so if offset is empty string (${1::1}), will still evaluate to 0. And instead a list of 2 simple expressions you can use a single compound expression: [ "$1" -a ${1::1} = ${1: -1} ]. Or in Bash-specific way: [[ $1 && ${1::1} = ${1: -1} ]]. The later having the advantage of not crashing when input contains whitespace characters. \$\endgroup\$
    – manatwork
    Mar 29, 2018 at 9:32
2
\$\begingroup\$

Fireball, 4 bytes

d1╡├

Explanation:

d      Duplicate implicit input
 1╡    Get the first character
   ├   Check whether the input ends with the first character

Alternative program:

d↔♥├
\$\endgroup\$
7
  • \$\begingroup\$ Explanation for the alternative program? \$\endgroup\$
    – MD XF
    May 13, 2017 at 20:36
  • \$\begingroup\$ @MDXF It's pretty much the same. gets the first n characters, 1 in this case, and ↔♥ just gets the first character. \$\endgroup\$
    – Okx
    May 13, 2017 at 20:37
  • \$\begingroup\$ I have removed the striked 6. If you want to show that there was a 6-byte version, please include it in the post, otherwise it doesn't make sense. ;) \$\endgroup\$ May 14, 2017 at 17:52
  • 3
    \$\begingroup\$ @EriktheOutgolfer I've seen plenty of answers where previous versions weren't shown in the answer, as there's a thing called revision history. Edit: Never mind, the 6 byte wasn't in the revision history. \$\endgroup\$
    – Okx
    May 14, 2017 at 18:08
  • \$\begingroup\$ @EriktheOutgolfer When you change your answer within 5 minutes you won't see the history of it. I had it a few times myself, posting an answer, realizing I can golf it 3 minutes later, and when you change it it's not showing any history, but it does show the crossed out byte-count of the previous answer. \$\endgroup\$ May 15, 2017 at 8:11
2
\$\begingroup\$

Pyth, 9 bytes

.xqhzez!1

Try it online!

Could make it 5 bytes if I didn't have to deal with "", probably even less if I was good at Pyth.

\$\endgroup\$
1
  • \$\begingroup\$ consistency @Svetlana it has to return a false value to keep with the false value returned by q \$\endgroup\$
    – clapp
    May 20, 2017 at 22:29
2
\$\begingroup\$

JavaScript (ES6), 25 bytes

s=>/^(.)(.*\1)?$/.test(s)

21 bytes if we can return true for the empty string.

s=>s[0]==[...s].pop()

Try it

f=
s=>/^(.)(.*\1)?$/.test(s)
o.innerText=f(i.value="10h01")
i.oninput=_=>o.innerText=f(i.value)
<input id=i><pre id=o>

\$\endgroup\$
1
  • \$\begingroup\$ Fails for test cases Acccca and wow!. I think this needs ^ and $ in the regex. \$\endgroup\$
    – nderscore
    May 13, 2017 at 18:52
2
\$\begingroup\$

Python 3, 31 24 Bytes

lambda a:a[0]==a[-1]!=''

Old code:

def f(a):return a[0]==a[-1]!=''

This is pretty self explanatory; It takes a string a and checks if the first and last chars are equal, but I then had to add the !='' in order to satisfy the requirement "The input can be empty String as well, for which you should return a falsey value" because Python returns True for an empty string.

EDIT:

  • -7 Bytes thanks to @numbermaniac
  • \$\endgroup\$
    4
    • 1
      \$\begingroup\$ You could save bytes by making this a lambda, so you wouldn't need the word return. \$\endgroup\$ May 20, 2017 at 2:09
    • \$\begingroup\$ I'm not so good at lambdas, I did originally consider doing it but I couldn't get them working: lambda a: a[0]==a[-1]!='' returns <function <lambda> at ...> \$\endgroup\$
      – AvahW
      May 20, 2017 at 10:10
    • 1
      \$\begingroup\$ Yeah, it returns a lambda function, which you can then assign to a variable to use. In this case, to use it would be f=lambda a: a[0]==a[-1]!='' and then simply f("whatever"). But you don't need to assign it to f to answer the question, so your lambda is fine. \$\endgroup\$ May 20, 2017 at 11:29
    • 1
      \$\begingroup\$ This gives an IndexError when called on an empty string. Not sure if that's within the rules. \$\endgroup\$
      – jqkul
      Jun 20, 2017 at 4:32
    2
    \$\begingroup\$

    Ruby, 16 17 bytes

    Outputs true or false. Now with fixed syntax error.

    p !! ~/./&~/#$&$/
    

    Try it online!

    \$\endgroup\$
    3
    • \$\begingroup\$ The TIO link gives a syntax error. If I add a space before ~ it runs, but it uses two different falsy values, which the OP forbids. \$\endgroup\$ May 20, 2017 at 1:44
    • \$\begingroup\$ p !!(~/./&&~/#$&$/) works. \$\endgroup\$ May 20, 2017 at 1:55
    • \$\begingroup\$ @ØrjanJohansen Fixed. I didn't use your solution, though; I found a shorter solution by leveraging Ruby's bitwise AND when literal true/false is the first operand. \$\endgroup\$
      – Value Ink
      May 22, 2017 at 19:36
    2
    \$\begingroup\$

    Casio Basic, 46 bytes

    StrLeft s,1,a
    StrRight s,1,b
    Print judge(a=b)
    

    Strings aren't very nice to work with in this language. We need to take the first character from the left and right of the string, assign them to a and b, then print whether a is equal to b.

    45 bytes for the code, 1 byte to enter s as parameter.

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

    C, 50 40 36 bytes

    Saved 10 bytes thanks to Dennis.

    #define f(s)(*s&&*s==s[strlen(s)-1])
    

    Equates to 0 if the first and last characters are different, or if the string is empty.

    You could call f with something like:

    int main(void)
    {
        char s[100] = {0};
        gets(s);
        printf("%d\n",f(s));
    }
    

    Or, try it online!

    \$\endgroup\$
    2
    • \$\begingroup\$ You could save one more byte by changing the logical AND (&&) comparison to a bitwise AND operation (&). \$\endgroup\$ May 14, 2017 at 11:11
    • 1
      \$\begingroup\$ @CodyGray I don't think that would work if *s was odd. \$\endgroup\$
      – Neil
      May 14, 2017 at 11:36
    2
    \$\begingroup\$

    PowerShell, 24 bytes

    !("$args"[0,-1]|gu).Rank
    

    Try it online!

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

    Labyrinth, 27 20 bytes

    ,)!@
     : !
    ,} _
    ")=-:
    

    Try it online!

    -7 bytes thanks to Jo King.

    Basic flow goes like this: start at the upper left corner, filter away the empty input at the first T-junction, take the rest of the string at the 2x2 loop, and test for equality at the last T-junction.

    How it works

    x marks the alternative paths at junctions, which should make the explanation easier to follow.

    ,)!@   Take char input (possibly EOF == -1), increment
     x     If EOF, top is 0, so go straight, print 0 and halt
    
     x     Otherwise, the string is not empty
     :     Duplicate the first char and move to aux. stack
    ,}     Go around the 2x2 loop `,")}`:
    ")x    Take next char input, increment, move to aux. stack
           until it hits EOF, where the stack is [first 0 | last ... first]
      @
      !    `=`: Swap the top of two stacks, giving [first last | (ignored)]
      _    Then calculate first - last
    x=-x   If nonzero, take the north branch `_!@`: Push 0, print, halt
    
    x)!@
     :     If zero, go all the way back to the first branch
    x} x   (Eventually print 1 and halt)
    x)=-:
    
    \$\endgroup\$
    0
    2
    \$\begingroup\$

    Lexurgy, 27 bytes

    a:
    ([]$1) []* !$1=>*
    []+=>a
    

    Outputs an empty string for falsey, and a otherwise.

    Explanation:

    a:                # change...
    ([]$1)            # the first character
           []*        # then 0 or more any character, regex /.*/
               !$1    # then a character that's not the first
                  =>* # change to an empty string
    # equivalent regex: /(.).*\1/
    []+=>a            # replace the leftovers with "a"
    
    \$\endgroup\$
    0
    2
    \$\begingroup\$

    Julia, 22 bytes

    !s=s>""&&s[1]==s[end]   

    Attempt This Online!

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

    MUMPS, 27 bytes

     w x]""&($e(x)=$e(x,$l(x)))
    

    Try it online!

    • There is a leading space character so w is interpreted as a command and not a label.
    • w is short for the write command which prints the following expression to the console.
    • x]"" checks that x is not empty. ] is the "follows" operator and everything non-empty follows the empty string.
    • $l is short for $length which returns the length of a string.
    • $e is short for $extract which gets characters from a string. $e(x) gets the first character of x and $e(x,$l(x)) gets the last character of x.

    It could be further reduced to 23 bytes in Intersystems Caché/IRIS by replacing $l(x) with *.

     w x]""&($e(x)=$e(x,*))
    
    \$\endgroup\$
    2
    • 1
      \$\begingroup\$ Welcome to Code Golf! For TIO, the Footer field will just be appended to the code, with a newline IIRC. The Input is just fed into the interpreter/compiled binary's STDIN, and each of the Arguments are command line options for the interpreted code/compiled binary. I'm not sure how MUMPS uses its STDIN/command line arguments, though. \$\endgroup\$ Jul 19, 2022 at 17:20
    • \$\begingroup\$ Thanks, that helped clear up a little confusion. I've never used M with command line arguments so I'll just have to figure that out. \$\endgroup\$ Jul 19, 2022 at 17:31
    2
    \$\begingroup\$

    C#, 25 21 bytes

    Uses the index operator ^ from C# 8 to get the last character in the string.

    x=>x!=""&&x[0]==x[^1]
    

    Try it online!

    -4 bytes thanks to the default

    \$\endgroup\$
    1
    • 2
      \$\begingroup\$ You can remove the parentheses around x and use x!="" instead of x.Any(). \$\endgroup\$ Aug 3, 2022 at 10:33
    1
    \$\begingroup\$

    Python 2, 36 35 bytes

    -1 byte thanks to Erik the Outgolfer

    lambda s:s[0]==s[-1]if s else False
    

    Try it online!

    \$\endgroup\$
    6
    • \$\begingroup\$ You can use and instead of conditionals and save many bytes: lambda s:s and s[0]==s[-1] \$\endgroup\$ May 13, 2017 at 17:57
    • \$\begingroup\$ If I try to golf further, I'll end up copying the other answers. \$\endgroup\$ May 13, 2017 at 18:26
    • \$\begingroup\$ @musicman523 that does not work for the empty string \$\endgroup\$
      – Mr. Xcoder
      May 13, 2017 at 18:31
    • \$\begingroup\$ @Mr.Xcoder It would return the empty string, I thought this would be considered a falsey value since bool('') == False \$\endgroup\$ May 13, 2017 at 20:38
    • 1
      \$\begingroup\$ @musicman523 Answers to this challenge have to choose a specific falsey value to return. You're not allowed to output '' for some inputs and False for others. \$\endgroup\$ May 14, 2017 at 7:56
    1
    \$\begingroup\$

    Python, 31 bytes

    lambda x:bool(x)and x[0]==x[-1]
    
    \$\endgroup\$
    3
    • \$\begingroup\$ You can eliminate the explicit call to bool and save 5 bytes: lambda x:x and x[0]==x[-1] \$\endgroup\$ May 13, 2017 at 17:55
    • \$\begingroup\$ @musicman523 It wouldn't follow the rules then. \$\endgroup\$ May 13, 2017 at 18:03
    • \$\begingroup\$ My bad (see thread above) \$\endgroup\$ May 14, 2017 at 8:00
    1
    \$\begingroup\$

    QBIC, 12 11 bytes

    ?_s;|=_s_fA
    

    Explanation:

    ?              PRINT
         =         -1 if equal, 0 if not, between
     _s;|          QBIC's Substring function takes a variable amount of parameters.
                     With only a string as argument it takes the leftmost char of it.
                     The ; takes a string from the cmd line and names it A$
                     | closes the call to Substring
          _s_fA    _f flips string A, _s without arguments takes the left 1 char again.
    

    Original 12 byter, which takes a substring of 1 from the left and 1 from the right:

    ?_s;|=_sA,-1
    

    Explanation of the second substring:

          _sA,-1   Another call to Substring
                     A$ is implicitly defined by the ; in the other substring
                     -1 sets the starting index at the last position
                     No argument for length = 1 char by default.
                   No closing |, auto-added at EOF
    
    \$\endgroup\$
    0
    1
    \$\begingroup\$

    Standard ML - 52 54 bytes

    open String
    fn s=>s<>""andalso sub(s,0)=sub(s,size s-1)
    
    \$\endgroup\$
    1
    • \$\begingroup\$ This raises uncaught exception Subscript, you need size s-1. \$\endgroup\$
      – Laikoni
      May 13, 2017 at 17:51
    1
    \$\begingroup\$

    CJam, 6

    q_W>#!
    

    Try it online

    Explanation:

    q_     read and duplicate the input
    W>     get the substring starting from the last position (W=-1)
            the result is empty if the input is empty
    #      find the position of that substring within the initial string
            a bit surprising, position of empty string within itself is -1 (not found)
    !      negate (0->1, non-zero->0)
    

    Note: I consider the behavior of # with an empty substring to be a bug in CJam⩽0.6.5 and I will probably fix it in the next version. It's useful for this challenge though.

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

    Excel, 38 bytes

    =1*IFERROR(CODE(A1)=CODE(RIGHT(A1)),0)
    

    Surprisingly longer than I expected, in order to get the same truthy/falsy for all cases. Text conditionals ignore case by default in excel, so "A"="a" is TRUE. Empty cells yield an error for CODE(). Multiplied by 1 to force everything to a number, rather than having TRUE, FALSE, or 0 cases.

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

    Batch, 52 bytes

    @set s=!=
    @set/ps=
    @if "%s:~,1%"=="%s:~-1%" echo 1
    

    Outputs 1 if equal, nothing if not. set/p doesn't change the variable if nothing is entered, so I can initialise it to a failure case, and != seemed appropriate.

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

    Ruby, 22 20 bytes

    ->x{x[0]===x[-1]||p}
    
    \$\endgroup\$
    0
    1
    \$\begingroup\$

    Java 8, 29 bytes

    s->s.matches("^(.)(.*\\1)?$")
    

    Port of @Neil's Retina answer.

    Try it here.

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

    C, 34 bytes

    f(char*s){s=*s&&*s==s[puts(s)-2];}
    

    Try it online

    C, 35 bytes

    f(char*s){s=*s&&!strrchr(s,*s)[1];}
    

    Try it online

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

    Brain-Flak, 51 bytes

    Includes +1 for -a

    {(<([({})<{({}<>)<>}<>>]{})((){[()](<{}>)}{})>)}{}
    

    Try it online!

    Outputs 1 on top of the stack for truthy, and either nothing or 0 on top of the stack for falsy. These are consistent with Brain-Flak's "if" statement: {...}.

    {(<                                          >)}{} # If there is input...
         ({})<            >                            #   Evaluate to the first char after...
              {({}<>)<>}<>                             #     reversing the entire stack
       ([                  ]{})((){[()](<{}>)}{})      # Check if the top 2 are equal
                                                       # I.e. first == last
    
    \$\endgroup\$
    1

    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.