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!

share|improve this question
4  
@Shaggy The empty string doesn't have a first and a last character at all, so how could they be equal if they don't exist at all? – Erik the Outgolfer 2 days ago
1  
I agree with @EriktheOutgolfer ... You should accept both True and False for "", because some languages return a truthy value in that case (Swift). – Mr. Xcoder 2 days ago
5  
I too don't see why the empty string should have any expected output. The start and end do not exist, they neither equal each other nor do they not equal each other. The title is "Does the start equal the end", the answer in the case in question is "I don't know", so the output should be allowed to be anything. – Jonathan Allan 2 days ago
1  
What is the point of specifying the output as "truthy/falsey" if you are later in the post going to amend that to "a single Truthy value and a single Falsey value"? – Jonathan Allan 2 days ago
2  
@JonathanAllan Doesn't that makes sense? If you are using pair of 0 and 1 for denoting Truthy and Falsey values, your program should always output 1 for inputs whose apt output should be Truthy and 0 for inputs whose apt output should be Falsey. So, you can't have a program which outputs 0/1 pair for most of input Strings, but for single-char string it outputs True (It should output 1). All I am trying to say is that you have the freedom to choose the Truthy/Falsey values, but they need to be consistent with all the inputs! If this isn't normal, then I am ready to edit (if not too late). – Arjun 2 days ago

56 Answers 56

Python 3, 23 bytes

s=input()
s[0]!=s[-1]<e

Output is via exit code, so 0 (success) is truthy and 1 (failure) is falsy. If this is acceptable, a byte can be saved.

Try it online!

How it works

First of all, if s is an empty string, s[0] will raise an IndexError, causing the program to fail.

For non-empty s, if the first and last characters are equal, s[0]!=s[-1] will evaluate to False, so the program exits cleanly and immediately.

Finally, if the characters are different, s[0]!=s[-1] will evaluate to True, causing the compairson s[-1]<e to be performed. Since e is undefined, that raises a NameError.

If backwards compatibility with Python 2 is not desired,

s[0]!=s[-1]<3

works as well, since comparing a string with an integer raises a TypeError.

share|improve this answer
    
Save 1 byte with lambda – OldBunny2800 yesterday
1  
Yes, a regular function would also save a byte. While output via exit code is an established consensus, non-error/error for a function is not though. I've linked to the proposal in my answer. – Dennis yesterday
    
What about using Python REPL? – OldBunny2800 yesterday
    
I don't think that helps. It's still not an exit code. – Dennis yesterday

Retina, 13 12 bytes

^(.)(.*\1)?$

Try it online! Includes test suite. Edit: Saved 1 byte thanks to @Kobi.

share|improve this answer
    
@Kobi It's so obvious now you point it out, but I just couldn't work out how to handle the case of a single character. – Neil 2 days ago

JavaScript, 19 bytes

a=>a.endsWith(a[0])
share|improve this answer
    
Wow. I didn't even know that there exists an endsWith method of String object. Nice! :) – Arjun yesterday
    
How did I forget about endsWith()?! I've been waiting for an opportunity to use it. – Shaggy 19 hours ago

Brachylog, 4 bytes

h~t?

Try it online!

Explanation

h       The head of the Input...
 ~t?    ...is the tail of the Input
share|improve this answer
1  
I really need to get round to implementing those constraint variables for the input; that'd mean we'd be able to do this in two. – ais523 2 days ago

Python 2, 26 25 24 bytes

Thanks to Dennis for saving a byte!

lambda x:""<x[:1]==x[-1]

Try it online!

share|improve this answer

05AB1E, 4 bytes

S¬Q¤

Try it online! or Try All Tests

S    # Split the input into individual characters
 ¬   # Get the first character
  Q  # Check all characters for equality to the first
   ¤ # Get the last value i.e. head == tail
share|improve this answer

Java, 81 77 bytes

  • -4 bytes, thanks @KevinCruijssen

Try Online

boolean f(String s){int l=s.length();return l>0&&s.charAt(l-1)==s.charAt(0);}
  • Returns true if they're equal, otherwise false, false for empty string

Array Version, 60 bytes

boolean f(char[]s){int l=s.length;return l>0&&s[0]==s[l-1];}
share|improve this answer
    
Why long instead of int? – corvus_192 2 days ago
    
@corvus_192 a unicode character can be 1-6 bytes. – Khaled.K 2 days ago
    
The difference between two chars can be at most Charcter.MAX_VALUE - Character.MIN_VALUE, which is 65535 – corvus_192 2 days ago
    
@corvus_192 I see, I've fixed it now – Khaled.K 2 days ago
    
You can change the -1 to 2. When it would output 2 you wouldn't know if it's because the difference between the first and last char is 2 or it's an empty String, but it doesn't matter for the challenge: Simply 0 = true; everything else = false is enough. – Kevin Cruijssen yesterday

MATL, 5 bytes

&=PO)

Try it at MATL Online!

Explanation

       % Implicitly grab input as a string (of length N)
&=     % Perform an element-wise equality check yielding an N x N matrix
P      % Flip this matrix up-down
O)     % Get the last value in the matrix (column-major ordering)
       % Implicitly display the result

In the case, that an empty input string must be handled, then something like the following (8 bytes) would work

&=POwhO)

This solution simply prepends a 0 to the front of the N x N matrix such that for an empty input, when the matrix is 0 x 0, there's still a 0 value that is then grabbed by 0)

Try it at MATL Online

share|improve this answer
    
Very clever approach! – Luis Mendo 2 days ago
    
Also 5 bytes: 5L)d~. – Sanchises yesterday
2  
Just a heads-up: neither my comment nor your answer handle empty input. This has (in my opinion convincincly) been argued against in the comments, so I expect this requirement to change. However, as it stands, this entry is invalid. – Sanchises yesterday
1  
(of course, you could do tn?&=PO)}F to deal with empty input; not sure if there is a more efficient way) – Sanchises yesterday

Mathematica, 15 bytes

#&@@#===Last@#&

Takes an array of chars. Throws errors when the input is empty but can be ignored.

share|improve this answer
2  
Nice job spotting the fact that === handles the empty case :) – Greg Martin 2 days ago

Haskell, 21 bytes

c takes a String and returns a Bool.

c s=take 1s==[last s]

Try it online!

  • If not for empty strings, this could have been 16 bytes with c s=s!!0==last s.
  • take 1s gives a list that is just the first element of s unless s is empty, in which case it's empty too.
  • last s would error out on an empty string, but Haskell's laziness saves it: A string with a single element is always different from the empty string, without evaluating its element.
share|improve this answer

PHP>=7.1, 23 Bytes

prints 1 for equal and nothing if the character is different

<?=$argn[0]==$argn[-1];
share|improve this answer

Swift, 57 bytes

var s=readLine()!,a=Array(s.characters);a[0]==a.last ?1:0
share|improve this answer
    
Edited the code. – Leena yesterday
    
Welcome to PPCG! Is the space after a.last necessary? – Hyper Neutrino yesterday
    
Either I can add brackets around a.last or I can add space after a.last – Leena 18 hours ago

APL (Dyalog), 4 bytes

⊃⌽=⊃

Try it online!

Explanation

  =                     Compare
   ⊃                    The first element of the right argument with
 ⌽                      The right argument reversed
                        This will return an array of the length of the reversed argument. Each element in the resulting array will be either 0 or 1 depending on whether the element at that position of the reversed argument equals the first element of the original right argument
                        So with argument 'abcda', we compare 'a' with each character in 'adcba' which results in the array 1 0 0 0 1
⊃                       From this result, pick the first element.

Here is the reason this works on empty strings. Applying to an empty string returns a space . But reversing an empty string still returns an empty string, so comparing an empty string with a non-empty string (in this case ) gives an empty numerical vector. And applying to an empty numerical vector returns 0. Hence passing an empty string returns 0.

share|improve this answer
    
This is actually really cool answer, but your explanation is not right. It would be right for (⊃⌽)=⊃ or ⊢/=⊃, but neither of those give the right result. Instead ⌽=⊃ compares the reversed string to its first character, and then picks the first element of that. If the string is empty, it ends up comparing a space to an empty string, which gives an empty Boolean list, of which the (coerced) first element is 0 – the correct answer for empty strings. Your expression is equivalent to ⊃⊃=⌽ because = is commutative. – Adám yesterday
    
@Adám Thank you for helping me see the mistake in my explanation. – Kritixi Lithos yesterday
    
You're welcome. Now your note is not correct. ⊃⌽=⊃ is not the same as (⊃⌽)=⊃. It is more expensive, as it compares all the elements instead of just the first and last. Also it wouldn't work had the OP used numbers instead of strings. – Adám yesterday
    
The first argument reversedThe right argument reversed – Adám yesterday
    
You may also want to explain why this works on empty strings. – Adám yesterday

C#, 38 30 bytes

s=>s!=""&&s[0]==s[s.Length-1];

Saved 8 bytes thanks to @raznagul.

share|improve this answer
1  
Instead of checking the length of s just compare it with "". Also you don't need the ?:-Operator. Using && has the same result. – raznagul 20 hours ago
    
@raznagul Good spots thanks, I can't check if it works at the moment so hopefully it does! Also wouldn't & have the same effect too? – TheLethalCoder 20 hours ago
    
@TheLeathalCoder: No just & doesn't work. With && the second expression is not validated if the first expression is false. With & the seconds expression is always validated and fails with a IndexOutOfRangeException on the empty string test case. – raznagul 20 hours ago
    
@raznagul Oh yeah... brain fart. – TheLethalCoder 20 hours ago
    
Perhaps its a bit late but you can save 5 bytes if you use s.Last() instead of s[s.Length-1] – Bojan B 46 mins ago

Java, 52 43 bytes

s->!s.isEmpty()&&s.endsWith(""+s.charAt(0))

To make it work, feed this into a function such as the following that makes a lambda "go":

private static boolean f(Function<String, Boolean> func, String value) {
  return func.apply(value);
}
share|improve this answer
1  
You can shave off 9 chars using s.endsWith(""+s.charAt(0)) instead of s.charAt(0)==s.charAt(s.length()-1) – SpaceBison yesterday
    
s->""!=s&&s.endsWith(""+s.charAt(0)) – JollyJoker yesterday
1  
@JollyJoker that does not work: try feeding new String() into the lambda. It will throw an exception. Reference semantics do not work here. – Snowman 14 hours ago

GNU grep, 12 bytes

^(.)(.*\1)?$

Run in extended or PCRE mode.

I don't know if this is considered cheating or not.

share|improve this answer
    
Does this handle the empty string case? – ConfusedMr_C 19 hours ago
    
@ConfusedMr_C Yep, empty string ⇒ code 1. – eush77 19 hours ago

JavaScript, 20 bytes

Add f= at the beginning and invoke like f(arg).

_=>_[0]==_.slice(-1)

f=_=>_[0]==_.slice(-1)

i.oninput = e => o.innerHTML = f(i.value);
<input id=i><pre id=o></pre>

Explanation

This function takes in an argument _. In the function body, _[0]==_.slice(-1) checks whether the first element of _ (at 0th index) equals the last element of it, and returns the appropriate true or false boolean.

share|improve this answer

brainfuck, 43 bytes

+>,[<,[>[->+<<->],]]<[[-]-<]-[----->+<]>--.

Try it online!

Explanation

The main loop is [>[->+<<->],]. After each iteration, the cell to the right of the current position is the first byte of the string, and the cell to the left is the difference between the most recently handled character and the first. <[[-]-<] converts the final result to -1 if nonzero, and the rest converts -1 and 0 to 48 and 49 ("0" and "1") respectively.

share|improve this answer

Japt, 6 bytes

tJ ¥Ug

Try it online!

share|improve this answer
    
Hmm, doesn't work for the empty string (should give false). I think you can fix this with tJ ¥Ug – ETHproductions 2 days ago

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.

share|improve this answer

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)
}
share|improve this answer
1  
I believe the rule is that you can use flags/options, but you need to include them in the byte count. – Ørjan Johansen 2 days ago

C++, 39 bytes

[](auto s){return s[0]&&s[0]==s.back();}

Full programs:

#include <string>
#include <iostream>

using namespace std;

int main()
{
    string t = "";
    auto f = [](auto s){return s[0]&&s[0]==s.back();};
    cout << f(t);
}

Try it online

share|improve this answer
    
I'm not the best in C++ (I typically use C), but could you change the instances of s[0] to *s to save two bytes each? – MD XF yesterday
    
@MDXF, that will only work with C type arrays. – Johan du Toit yesterday

Python, 51 bytes

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

Try it online!

share|improve this answer
    
Welcome to PPCG and nice first answer! This solution can be golfed by not using if-else statements like so: Try it online! – Kritixi Lithos 2 days ago

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 $?
share|improve this answer

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↔♥├
share|improve this answer
    
Explanation for the alternative program? – MD XF 2 days ago
    
@MDXF It's pretty much the same. gets the first n characters, 1 in this case, and ↔♥ just gets the first character. – Okx 2 days ago
    
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 yesterday
2  
@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 yesterday
    
@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 yesterday

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!

share|improve this answer
    
You could save one more byte by changing the logical AND (&&) comparison to a bitwise AND operation (&). – Cody Gray 2 days ago
1  
@CodyGray I don't think that would work if *s was odd. – Neil 2 days ago

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.

share|improve this answer

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>

share|improve this answer
    
Fails for test cases Acccca and wow!. I think this needs ^ and $ in the regex. – nderscore 2 days ago

Ruby, 26 24 bytes (thanks to @philomory)

->e{!!e[0]>0&&e[0]==e[-1]}

First post on codegolf -))

share|improve this answer
1  
Welcome to PPCG! – Martin Ender 21 hours ago
1  
Welcome to PPCG! Nice first golf. Good luck for future! – Arjun 18 hours ago
1  
You could save 4 bytes by just doing e[0]&&e[0]==e[-1], since if e is empty, e[0] will be nil. Actually, come to think of it, nil is no good since it's falsey but not the same falsey that the comparison returns; still, after adding !! you're still saving 2 characters. – philomory 9 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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