36
\$\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
"wow!"         Falsey
"wow"          Truthy
"H"            Truthy
""             Falsey

This is , so the shortest code in bytes wins!

\$\endgroup\$
  • \$\begingroup\$ What characters can appear in the input? Printable ASCII? \$\endgroup\$ – Martin Ender May 13 '17 at 19:35
  • \$\begingroup\$ @MartinEnder Printable ASCII. Although, I don't think it matters much. \$\endgroup\$ – Arjun Jun 3 '17 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\$ – Martin Ender Jun 3 '17 at 17:31
  • \$\begingroup\$ @MartinEnder Okay. Will take care in future. \$\endgroup\$ – Arjun Jun 4 '17 at 7:16
  • \$\begingroup\$ Suggested test case: AbAb => false \$\endgroup\$ – caird coinheringaahing Oct 31 '17 at 14:40

82 Answers 82

2
\$\begingroup\$

Python, 51 bytes

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

Try it online!

\$\endgroup\$
  • 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\$ – Kritixi Lithos May 14 '17 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\$
  • \$\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 '18 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\$
  • \$\begingroup\$ Explanation for the alternative program? \$\endgroup\$ – MD XF May 13 '17 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 '17 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\$ – Erik the Outgolfer May 14 '17 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 '17 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\$ – Kevin Cruijssen May 15 '17 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\$
  • \$\begingroup\$ consistency @Svetlana it has to return a false value to keep with the false value returned by q \$\endgroup\$ – clap May 20 '17 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\$
  • \$\begingroup\$ Fails for test cases Acccca and wow!. I think this needs ^ and $ in the regex. \$\endgroup\$ – nderscore May 13 '17 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\$
    • 1
      \$\begingroup\$ You could save bytes by making this a lambda, so you wouldn't need the word return. \$\endgroup\$ – numbermaniac May 20 '17 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\$ – sonrad10 May 20 '17 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\$ – numbermaniac May 20 '17 at 11:29
    • \$\begingroup\$ This gives an IndexError when called on an empty string. Not sure if that's within the rules. \$\endgroup\$ – bkul Jun 20 '17 at 4:32
    2
    \$\begingroup\$

    Ruby, 16 17 bytes

    Outputs true or false. Now with fixed syntax error.

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

    Try it online!

    \$\endgroup\$
    • \$\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\$ – Ørjan Johansen May 20 '17 at 1:44
    • \$\begingroup\$ p !!(~/./&&~/#$&$/) works. \$\endgroup\$ – Ørjan Johansen May 20 '17 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 '17 at 19:36
    2
    \$\begingroup\$

    shortC, 27 26 25 24 bytes

    f(C*s){T*s&&*s==s[Ss)-1]
    

    How it works:

    f(C*s){                     declare int-returning function that takes a string
           T                    return
            *s                  provided string has any length
              &&                and
                *s==s[Ss)-1]    the first character equals the last one
    

    Try it online!

    \$\endgroup\$
    • 2
      \$\begingroup\$ Wouldn't it be T instead of R? \$\endgroup\$ – Okx May 13 '17 at 20:34
    • \$\begingroup\$ @Okx Wow, can't believe I missed that!! Thanks! \$\endgroup\$ – MD XF May 13 '17 at 20:34
    • 1
      \$\begingroup\$ @MDXF, I like your shortC concept! I will be sending you some suggestions. \$\endgroup\$ – Johan du Toit May 15 '17 at 18:23
    • \$\begingroup\$ Yes, will chat soon. \$\endgroup\$ – Johan du Toit May 15 '17 at 18:32
    • \$\begingroup\$ For me it is not ok for gain just one char make possible "Ss)-1" it has to be "S(s)-1"...(if I understand well...) \$\endgroup\$ – RosLuP May 20 '17 at 9:20
    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\$
    • \$\begingroup\$ You could save one more byte by changing the logical AND (&&) comparison to a bitwise AND operation (&). \$\endgroup\$ – Cody Gray May 14 '17 at 11:11
    • 1
      \$\begingroup\$ @CodyGray I don't think that would work if *s was odd. \$\endgroup\$ – Neil May 14 '17 at 11:36
    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\$
    • \$\begingroup\$ You can use and instead of conditionals and save many bytes: lambda s:s and s[0]==s[-1] \$\endgroup\$ – musicman523 May 13 '17 at 17:57
    • \$\begingroup\$ If I try to golf further, I'll end up copying the other answers. \$\endgroup\$ – totallyhuman May 13 '17 at 18:26
    • \$\begingroup\$ @musicman523 that does not work for the empty string \$\endgroup\$ – Mr. Xcoder May 13 '17 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\$ – musicman523 May 13 '17 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\$ – undergroundmonorail May 14 '17 at 7:56
    1
    \$\begingroup\$

    Python, 31 bytes

    lambda x:bool(x)and x[0]==x[-1]
    
    \$\endgroup\$
    • \$\begingroup\$ You can eliminate the explicit call to bool and save 5 bytes: lambda x:x and x[0]==x[-1] \$\endgroup\$ – musicman523 May 13 '17 at 17:55
    • \$\begingroup\$ @musicman523 It wouldn't follow the rules then. \$\endgroup\$ – Erik the Outgolfer May 13 '17 at 18:03
    • \$\begingroup\$ My bad (see thread above) \$\endgroup\$ – musicman523 May 14 '17 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\$
    1
    \$\begingroup\$

    Standard ML - 52 54 bytes

    open String
    fn s=>s<>""andalso sub(s,0)=sub(s,size s-1)
    
    \$\endgroup\$
    • \$\begingroup\$ This raises uncaught exception Subscript, you need size s-1. \$\endgroup\$ – Laikoni May 13 '17 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\$
    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\$
    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
    \$\begingroup\$

    Perl 5: 28 bytes

    exit$ARGV[0]=~/^(.)(.*\1)?$/
    

    Similar to perl 6 but it seems to be shorter as a program.

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

    PowerShell, 42 bytes

    $a=(read-host);$a-ne""-and$a[0]-ceq$a[-1]
    
    \$\endgroup\$
    1
    \$\begingroup\$

    Brain-Flak, 55 bytes

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

    Try it online!

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

    Actually, 10 bytes

    ;;lb)F@N=*
    

    Try it online!

    Explanation:

    ;;lb)F@N=*
    ;;          copy input twice
      lb        length of input, cast to boolean
        )F      first character
          @N    last character
            =   compare equality
             *  multiply by boolean casted length (to make empty strings falsey)
    
    \$\endgroup\$
    • \$\begingroup\$ This fails for an empty string. \$\endgroup\$ – Ørjan Johansen May 16 '17 at 0:39
    • \$\begingroup\$ @ØrjanJohansen Fixed \$\endgroup\$ – Mego May 16 '17 at 1:07
    1
    \$\begingroup\$

    REXX 32 Bytes

    a=arg(1)
    say abbrev(a,right(a,1))
    

    Tests if the last character is a valid abbreviation of the whole string.

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

    Chip, 91+3 = 94 bytes

    *Z~.
    ,-{mA
    >{xmB
    |BA|
    |CD|AvB
    >{xmC+G
    >-{mD+H
    >{-mE+~t
    >x{mF^S
    |EF|
    |HG|
    >x{mG
    >{-mH
    Z--)~a
    

    +3 for -z

    Outputs the byte 0x0 for falsey, and 0x1 for truthy. This is a lot bigger than I was hoping, sadly.

    Try it online! (Note about the TIO: it includes an extra line e*f to map the output to ASCII digits. TIO also includes the verbose flag -v, which gives extra debug output via stderr.)

    The first line produces a signal on only the first byte, allowing us to store that byte's bits, and to detect the empty string. (If we could give a truthy value for the empty string, -3 bytes.)

    The last line deals with output, producing truthy only if the first and most recent bytes match, and if it isn't the first byte. Output is given one byte after the end of the input, with the help of -z. If not, we would be unable to detect the end of the string. (If we swapped truthy and falsey, -2 bytes, or if combined with empty string savings above, -4 for the both.)

    The blob to the right, surrounding the +'s, is what triggers the end of input behavior. This actually looks for a zero byte, meaning that incorrect results may occur if one is given as input.

    The remainder of the elements perform the actual comparison. This comparison performed is equivalent to, in C-ish: !(input[0] xor input[n]). In Chip, however, this must be performed for each bit individually, hence the eight sets of memory cells m, xor-gates {, and so on.

    There is an interesting caveat to this implementation, in that it can handle 8 bits, but is unaware of unicode. So, effectively, this compares the first and last bytes, rather than chars.

    \$\endgroup\$
    • \$\begingroup\$ Uh! That's a lot of explanation! Thanks for that! :) \$\endgroup\$ – Arjun May 19 '17 at 16:26
    • \$\begingroup\$ Yeah, but I figured it would be rather opaque without it. As far as I'm aware, I'm the only one that's used this language more than trivially. :P \$\endgroup\$ – Phlarx May 19 '17 at 16:29
    1
    \$\begingroup\$

    Axiom, 30 bytes

    f(a)==(#a=0=>false;a.1=a.(#a))
    

    this below seems not to be ok

    f(a)==(#a=0=>false;a.#a=a.1)
    
    \$\endgroup\$
    1
    \$\begingroup\$

    TI-Basic (TI-84 Plus CE), 17 bytes

    sub(Ans,1,1)=sub(Ans,length(Ans),1
    

    Run with "string":prgmNAME. Returns 1 for true and 0 for false.

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

    J, 12 bytes

    '({.={:)*.*@#
    

    {. means start, = means equals, and {: means end. *.*@# means "logical and with the length of the string", i.e., if the length is 0, it returns 0.

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