# Does the start equal the end?

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.

• 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!

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

## 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)
}

• I believe the rule is that you can use flags/options, but you need to include them in the byte count. – Ørjan Johansen May 14 '17 at 4:45

# Python, 51 bytes

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


Try it online!

• Welcome to PPCG and nice first answer! This solution can be golfed by not using if-else statements like so: Try it online! – user41805 May 14 '17 at 9:45

# 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$?

• 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. – manatwork Mar 29 '18 at 9:32 # 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↔♥├  • Explanation for the alternative program? – MD XF May 13 '17 at 20:36 • @MDXF It's pretty much the same. ╡ gets the first n characters, 1 in this case, and ↔♥ just gets the first character. – Okx May 13 '17 at 20:37 • 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. ;) – Erik the Outgolfer May 14 '17 at 17:52 • @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. – Okx May 14 '17 at 18:08 • @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. – Kevin Cruijssen May 15 '17 at 8:11 # 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. • consistency @Svetlana it has to return a false value to keep with the false value returned by q – clapp May 20 '17 at 22:29 # 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> • Fails for test cases Acccca and wow!. I think this needs ^ and $ in the regex. – nderscore May 13 '17 at 18:52

# 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
• You could save bytes by making this a lambda, so you wouldn't need the word return. – numbermaniac May 20 '17 at 2:09
• 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 ...> – sonrad10 May 20 '17 at 10:10
• 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. – numbermaniac May 20 '17 at 11:29
• This gives an IndexError when called on an empty string. Not sure if that's within the rules. – jqblz Jun 20 '17 at 4:32

# Ruby, 16 17 bytes

Outputs true or false. Now with fixed syntax error.

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


Try it online!

• 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. – Ørjan Johansen May 20 '17 at 1:44
• p !!(~/./&&~/#$&$/) works. – Ørjan Johansen May 20 '17 at 1:55
• @Ø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. – Value Ink May 22 '17 at 19:36

# shortC, 272625 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!

• Wouldn't it be T instead of R? – Okx May 13 '17 at 20:34
• @Okx Wow, can't believe I missed that!! Thanks! – MD XF May 13 '17 at 20:34
• @MDXF, I like your shortC concept! I will be sending you some suggestions. – Johan du Toit May 15 '17 at 18:23
• Yes, will chat soon. – Johan du Toit May 15 '17 at 18:32
• 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...) – user58988 May 20 '17 at 9:20

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

# C, 5040 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));
}

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

# PowerShell, 24 bytes

!("$args"[0,-1]|gu).Rank  Try it online! # 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)=-:  # 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! • You can use and instead of conditionals and save many bytes: lambda s:s and s[0]==s[-1] – musicman523 May 13 '17 at 17:57 • If I try to golf further, I'll end up copying the other answers. – totallyhuman May 13 '17 at 18:26 • @musicman523 that does not work for the empty string – Mr. Xcoder May 13 '17 at 18:31 • @Mr.Xcoder It would return the empty string, I thought this would be considered a falsey value since bool('') == False – musicman523 May 13 '17 at 20:38 • @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. – undergroundmonorail May 14 '17 at 7:56 # Python, 31 bytes lambda x:bool(x)and x[0]==x[-1]  • You can eliminate the explicit call to bool and save 5 bytes: lambda x:x and x[0]==x[-1] – musicman523 May 13 '17 at 17:55 • @musicman523 It wouldn't follow the rules then. – Erik the Outgolfer May 13 '17 at 18:03 • My bad (see thread above) – musicman523 May 14 '17 at 8:00 ## 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  # Standard ML - 52 54 bytes open String fn s=>s<>""andalso sub(s,0)=sub(s,size s-1)  • This raises uncaught exception Subscript, you need size s-1. – Laikoni May 13 '17 at 17:51 # 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. ## 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. ## 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. # Ruby, 22 20 bytes ->x{x[0]===x[-1]||p}  # Java 8, 29 bytes s->s.matches("^(.)(.*\\1)?$")


Try it here.

# 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

# 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

• – James May 15 '17 at 20:56

# Perl 5: 28 bytes

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


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

# PowerShell, 42 bytes

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


# Brain-Flak, 55 bytes

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


Try it online!

# 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)

• This fails for an empty string. – Ørjan Johansen May 16 '17 at 0:39
• @ØrjanJohansen Fixed – user45941 May 16 '17 at 1:07

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

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

• Uh! That's a lot of explanation! Thanks for that! :) – Arjun May 19 '17 at 16:26
• 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 – Phlarx May 19 '17 at 16:29