Does the start equal the end?

36

6

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!

Arjun

Posted 2017-05-13T17:03:04.243

Reputation: 4 544

What characters can appear in the input? Printable ASCII? – Martin Ender – 2017-05-13T19:35:12.627

@MartinEnder Printable ASCII. Although, I don't think it matters much. – Arjun – 2017-06-03T17:29:44.120

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 [tag:string] tag, specify exactly what characters can appear in the input. – Martin Ender – 2017-06-03T17:31:55.477

@MartinEnder Okay. Will take care in future. – Arjun – 2017-06-04T07:16:24.867

Suggested test case: AbAb => false – caird coinheringaahing – 2017-10-31T14:40:12.613

Answers

5

Jelly, 3 bytes

=ṚḢ

Try it online!

Erik the Outgolfer

Posted 2017-05-13T17:03:04.243

Reputation: 38 134

17

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.

Dennis

Posted 2017-05-13T17:03:04.243

Reputation: 196 637

Save 1 byte with lambda – OldBunny2800 – 2017-05-14T23:07:42.487

1Yes, 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 – 2017-05-14T23:12:07.980

What about using Python REPL? – OldBunny2800 – 2017-05-14T23:13:14.110

I don't think that helps. It's still not an exit code. – Dennis – 2017-05-15T00:25:02.633

9

JavaScript, 19 bytes

a=>a.endsWith(a[0])

Bald Bantha

Posted 2017-05-13T17:03:04.243

Reputation: 463

Wow. I didn't even know that there exists an endsWith method of String object. Nice! :) – Arjun – 2017-05-15T02:45:05.597

How did I forget about endsWith()?! I've been waiting for an opportunity to use it. – Shaggy – 2017-05-15T16:38:38.633

7

Retina, 13 12 bytes

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

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

Neil

Posted 2017-05-13T17:03:04.243

Reputation: 95 035

7

Mathematica, 15 bytes

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

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

JungHwan Min

Posted 2017-05-13T17:03:04.243

Reputation: 13 290

4Nice job spotting the fact that === handles the empty case :) – Greg Martin – 2017-05-13T19:01:04.487

7

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

Riley

Posted 2017-05-13T17:03:04.243

Reputation: 11 345

1ÂâćüQ to be more confusing and to gain a byte! – Magic Octopus Urn – 2017-05-16T19:08:03.917

ćsθQ is another 4-byter. – Magic Octopus Urn – 2018-03-28T17:08:44.927

7

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

Johan du Toit

Posted 2017-05-13T17:03:04.243

Reputation: 1 524

1I'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 – 2017-05-14T19:43:25.507

1@MDXF, that will only work with C type arrays. – Johan du Toit – 2017-05-15T11:05:50.210

6

Brachylog, 4 bytes

h~t?

Try it online!

Explanation

h       The head of the Input...
 ~t?    ...is the tail of the Input

Fatalize

Posted 2017-05-13T17:03:04.243

Reputation: 32 976

1I 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. – None – 2017-05-13T17:25:36.633

6

Python 2, 26 25 24 bytes

Thanks to @Dennis for saving a byte!

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

Try it online!

Adnan

Posted 2017-05-13T17:03:04.243

Reputation: 41 965

6

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];}

Khaled.K

Posted 2017-05-13T17:03:04.243

Reputation: 1 435

Why long instead of int? – corvus_192 – 2017-05-14T10:30:34.097

@corvus_192 a unicode character can be 1-6 bytes. – Khaled.K – 2017-05-14T10:33:06.110

The difference between two chars can be at most Charcter.MAX_VALUE - Character.MIN_VALUE, which is 65535 – corvus_192 – 2017-05-14T10:39:51.160

@corvus_192 I see, I've fixed it now – Khaled.K – 2017-05-14T11:21:28.293

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 – 2017-05-15T07:40:14.957

Hmm, nevermind my previous comment.. I just read this rule in the challenge: "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.", which means your current answer is also not valid by returning the difference between the chars. It should become something like int f(String s){int l=s.length();return l>0&&s.charAt(l-1)-s.charAt(0)==0?1:0;} or just a boolean for the same byte-count: boolean f(String s){int l=s.length();return l>0&&s.charAt(l-1)-s.charAt(0)==0;} – Kevin Cruijssen – 2017-05-15T08:07:54.213

1@KevinCruijssen For the last, s.charAt(l-1)==s.charAt(0) would save two bytes. – JollyJoker – 2017-05-15T10:56:28.470

An empty String is "", so boolean f(String s){return s!=""&&s.charAt(s.length()-1)==s.charAt(0);} would work, right? – JollyJoker – 2017-05-15T11:03:16.770

@JollyJoker yes, I've changed it now, also -1 byte by inverting the check to return""!=s to remove the space – Khaled.K – 2017-05-15T11:10:36.223

@JollyJoker nononononono! This fails for f(new String("")); You cannot assume that the strings are interned! – Socratic Phoenix – 2017-05-15T15:56:01.047

@SocraticPhoenix you're right, I've fixed it now. – Khaled.K – 2017-05-15T16:15:39.357

@SocraticPhoenix Ok, you're right. And equals becomes too long so declaring the length as an int is better. – JollyJoker – 2017-05-16T08:44:13.097

@SocraticPhoenix Then again, with all the "takes input as unary from the command line"-type restrictions in code golf answers, requiring interned strings should be a standard trick for java golfing :) – JollyJoker – 2017-05-16T10:52:42.447

@JollyJoker possible, except that'd require writing a full program. – Khaled.K – 2017-05-16T11:05:45.110

@JollyJoker I feel that the distinction there is that one requires a specific method of input, versus requiring a specific instance of an object which resides in the string pool. – Socratic Phoenix – 2017-05-16T13:49:23.883

5

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

Suever

Posted 2017-05-13T17:03:04.243

Reputation: 10 257

Very clever approach! – Luis Mendo – 2017-05-13T18:09:05.620

Also 5 bytes: 5L)d~. – Sanchises – 2017-05-14T15:24:57.537

2Just 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 – 2017-05-14T15:29:47.997

1(of course, you could do tn?&=PO)}F to deal with empty input; not sure if there is a more efficient way) – Sanchises – 2017-05-14T15:33:19.700

5

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.

Nitrodon

Posted 2017-05-13T17:03:04.243

Reputation: 9 181

5

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.

Ørjan Johansen

Posted 2017-05-13T17:03:04.243

Reputation: 6 914

4

Japt, 6 bytes

tJ ¥Ug

Try it online!

Luke

Posted 2017-05-13T17:03:04.243

Reputation: 4 675

Hmm, doesn't work for the empty string (should give false). I think you can fix this with tJ ¥Ug – ETHproductions – 2017-05-13T19:31:46.400

4

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.

user41805

Posted 2017-05-13T17:03:04.243

Reputation: 16 320

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 – 2017-05-15T11:34:02.227

@Adám Thank you for helping me see the mistake in my explanation. – user41805 – 2017-05-15T11:41:49.127

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 – 2017-05-15T11:44:15.760

The first argument reversedThe right argument reversed – Adám – 2017-05-15T11:44:54.057

You may also want to explain why this works on empty strings. – Adám – 2017-05-15T11:45:34.297

@Adám I added the explanation on empty strings, is it correct? – user41805 – 2017-05-15T12:13:25.903

Yes, that is correct. Now you just need to rephrase an array comparing equality between the first character of the argument with its reverse. You are not comparing the equality ;-) – Adám – 2017-05-15T12:16:03.680

4

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

user18932

Posted 2017-05-13T17:03:04.243

Reputation:

1You can shave off 9 chars using s.endsWith(""+s.charAt(0)) instead of s.charAt(0)==s.charAt(s.length()-1) – SpaceBison – 2017-05-15T08:32:15.260

s->""!=s&&s.endsWith(""+s.charAt(0)) – JollyJoker – 2017-05-15T11:06:51.203

1@JollyJoker that does not work: try feeding new String() into the lambda. It will throw an exception. Reference semantics do not work here. – None – 2017-05-15T20:58:55.747

2@KevinCruijssen The short circuiting effect of && is necessary to avoid an index out of bounds exception on the charAt(0) for an empty string – PunPun1000 – 2017-05-22T13:03:00.460

4

Ruby, 26 24 bytes

Saved two bytes thanks to @philomory!

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

First post on codegolf -))

marmeladze

Posted 2017-05-13T17:03:04.243

Reputation: 227

1Welcome to PPCG! – Martin Ender – 2017-05-15T14:36:16.547

1Welcome to PPCG! Nice first golf. Good luck for future! – Arjun – 2017-05-15T17:17:17.667

1You 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 – 2017-05-16T02:49:00.530

3

PHP>=7.1, 23 Bytes

prints 1 for equal and nothing if the character is different

<?=$argn[0]==$argn[-1];

Jörg Hülsermann

Posted 2017-05-13T17:03:04.243

Reputation: 13 026

3

C#, 38 30 bytes

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

Saved 8 bytes thanks to @raznagul.

TheLethalCoder

Posted 2017-05-13T17:03:04.243

Reputation: 6 930

1Instead of checking the length of s just compare it with "". Also you don't need the ?:-Operator. Using && has the same result. – raznagul – 2017-05-15T15:28:55.730

@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 – 2017-05-15T15:32:11.467

@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 – 2017-05-15T15:38:54.937

@raznagul Oh yeah... brain fart. – TheLethalCoder – 2017-05-15T15:40:38.647

Perhaps its a bit late but you can save 5 bytes if you use s.Last() instead of s[s.Length-1] – Bojan B – 2017-05-16T11:04:16.143

@BojanB No I can't because I then have to include using System.Linq; into the byte count. – TheLethalCoder – 2017-05-16T11:15:00.710

@TheLethalCoder, Oh Right, I keep forgetting about the usings – Bojan B – 2017-05-16T11:21:00.333

@BojanB No worries it takes a little bit to get used to what needs and doesn't need to be included in the byte count. And of course it changes between questions and their specs. – TheLethalCoder – 2017-05-16T11:21:51.040

3

Swift, 57 bytes

var s=readLine()!,a=Array(s.characters);a[0]==a.last ?1:0

Leena

Posted 2017-05-13T17:03:04.243

Reputation: 131

Edited the code. – Leena – 2017-05-14T17:23:17.553

Welcome to PPCG! Is the space after a.last necessary? – HyperNeutrino – 2017-05-14T22:11:06.673

Either I can add brackets around a.last or I can add space after a.last – Leena – 2017-05-15T16:55:44.933

3

R, 40 bytes

function(x)x>""&&rev(y<-charToRaw(x))==y

Thanks to Nitrodon for -2 bytes.

Thanks to MickyT for -8 bytes.

Test:

f=function(x)x>""&&rev(y<-charToRaw(x))==y
test <- c("10h01", "Nothing", "Acccca", "wow!", "wow", "H", "")
sapply(test, f)
all(sapply(test, f) == c(T, F, F, F, T, T, F))

Output:

> f=function(x)x>""&&rev(y<-charToRaw(x))==y
> test <- c("10h01", "Nothing", "Acccca", "wow!", "wow", "H", "")
> sapply(test, f)
  10h01 Nothing  Acccca    wow!     wow       H         
   TRUE   FALSE   FALSE   FALSE    TRUE    TRUE   FALSE 
> all(sapply(test, f) == c(T, F, F, F, T, T, F))
[1] TRUE

djhurio

Posted 2017-05-13T17:03:04.243

Reputation: 1 113

2You can remove one set of parentheses with rev(y<-el(strsplit(x,"")))==y. – Nitrodon – 2017-05-15T03:57:27.307

1also unnamed functions are acceptable, so you can remove the f= – MickyT – 2017-05-15T20:35:25.797

1and charToRaw can be used to split the string for comparison function(x)x>""&&rev(y<-charToRaw(x))==y – MickyT – 2017-05-15T20:50:19.440

3

><>, 39 33 bytes

 2i&01. >~&-?v1v
  i:1+?!^01. >0>n;

This is my first time both using ><> and playing code golf, so helpful suggestions would be appreciated.

The code is in three basic sections.

2i&01. Pushes an arbitrary number (2 in this case, this causes an empty string to print 0) onto the stack and puts the input's first character in the register.

>i:1+?!^01. Main loop. Pushes the next character onto the stack. If the string has been read completely, then go to the last section

>~&-?v1v
     >0>n;  Compare the first and last characters. Print 1 if they're the same, 0 if not

AGourd

Posted 2017-05-13T17:03:04.243

Reputation: 271

Hello! Welcome to PPCG! Nice first golf! Good luck for future! :) – Arjun – 2017-05-17T09:46:51.440

3

Google Sheets, 33 Bytes

Takes input from cell [A1] and outputs 1 for truthy input and 0 for falsey input.

=(A1<>"")*Exact(Left(A1),Right(A1

It is noted that the parentheticals in Exact( and Right( are left unclosed as Google Sheets automatically corrects this as soon as the user has input the formula text and pressed enter to leave that cell.

Output

GS Version

Taylor Scott

Posted 2017-05-13T17:03:04.243

Reputation: 6 709

Does the version of Excel matter? In my copy of 2013, this fails because you can't use & like that. Also, it considers A=a to be true. The shortest I can get is 38 bytes: =AND(EXACT(LEFT(A1),RIGHT(A1)),A1<>"") or the alternative =IFERROR(CODE(A1)=CODE(RIGHT(A1)),1=0). – Engineer Toast – 2018-03-26T18:43:44.280

I tried it in Excel Online (16.0.9222.5051) and it returns TRUE for any non-error input. (screenshot) Does it work in your copy for all test cases? ExcelGuy has an answer that ends up like mine above for the same reasons.

– Engineer Toast – 2018-03-27T14:24:13.430

1@EngineerToast you are completely correct, I should have been using * instead & for the binary and statement, but that still leaves the "A"="a" issue, which I had completely overlooked. All of that and a bit of syntax corrections leads me to =EXACT(LEFT(A1),RIGHT(A1))*(A1<>"") for 35, but I have switched the language to Google Sheets, which allowed me to drop the terminal double parenthetical in the Exact statement, rendering =(A1<>"")*Exact(Left(A1),Right(A1 for 33 bytes – Taylor Scott – 2018-03-28T17:06:23.213

3

R, 50 43 41 40 64

Second solution with 41 bytes for a callable function - thanks to @niczky12 & @Giuseppe - amended for x=""

r=function(x,y=utf8ToInt(x))ifelse(x=="","FALSE",(y==rev(y))[1])

First with 50 bytes but not for the challenge

function(x){charToRaw(x)[1]==rev(charToRaw(x))[1]}

Riccardo Camon

Posted 2017-05-13T17:03:04.243

Reputation: 41

You can replace charToRaw with utf8ToInt to produce NAs when the string is empty. – niczky12 – 2018-03-27T10:09:31.240

You can also remove the curly braces {} around the function body. – Giuseppe – 2018-03-27T10:13:16.550

I think (y==rev(y))[1] is shorter by a byte – Giuseppe – 2018-03-28T00:44:03.207

This challenge requires using only one Truthy and one Falsey value, but this produces NA for empty string but FALSE for "ab". Try it online!.

– Ørjan Johansen – 2018-03-28T17:21:10.413

@ØrjanJohansen thanks for your comment, so "ab" should not give FALSE? – Riccardo Camon – 2018-03-28T20:26:00.643

It may give FALSE, but then the empty string must give FALSE too. I don't really know R, but reading and testing more I don't think you can use NA, because it doesn't seem to be "falsey" in if() expressions, which is the accepted PPCG definition.

– Ørjan Johansen – 2018-03-29T00:20:42.020

2

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.

Arjun

Posted 2017-05-13T17:03:04.243

Reputation: 4 544

2

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↔♥├

Okx

Posted 2017-05-13T17:03:04.243

Reputation: 15 025

Explanation for the alternative program? – MD XF – 2017-05-13T20:36:40.293

@MDXF It's pretty much the same. gets the first n characters, 1 in this case, and ↔♥ just gets the first character. – Okx – 2017-05-13T20:37:56.957

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 – 2017-05-14T17:52:43.240

3@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 – 2017-05-14T18:08:03.467

@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 – 2017-05-15T08:11:20.257

@KevinCruijssen I know that happens, except if someone else comments. Anyways it didn't make sense at all right there. – Erik the Outgolfer – 2017-05-15T10:40:28.073

Sorry to bother, but if I may ask, what has happened to the Fireball repo? – ETHproductions – 2018-02-14T02:04:52.467

2

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>

Shaggy

Posted 2017-05-13T17:03:04.243

Reputation: 24 623

Fails for test cases Acccca and wow!. I think this needs ^ and $ in the regex. – nderscore – 2017-05-13T18:52:35.603

2

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.

Stewie Griffin

Posted 2017-05-13T17:03:04.243

Reputation: 43 471

2

GNU grep, 12 bytes

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

Run in extended or PCRE mode.

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

eush77

Posted 2017-05-13T17:03:04.243

Reputation: 1 280

Does this handle the empty string case? – clap – 2017-05-15T15:55:45.147

@ConfusedMr_C Yep, empty string ⇒ code 1. – eush77 – 2017-05-15T16:44:32.257

2

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.

shadowtalker

Posted 2017-05-13T17:03:04.243

Reputation: 461

1Suggest if instead of and and (mismatch(reverse s)s) instead of (mismatch s(reverse s)) – ceilingcat – 2018-03-27T03:43:57.057

2

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!

Leaky Nun

Posted 2017-05-13T17:03:04.243

Reputation: 45 011

2

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

shadowtalker

Posted 2017-05-13T17:03:04.243

Reputation: 461

1I believe the rule is that you can use flags/options, but you need to include them in the byte count. – Ørjan Johansen – 2017-05-14T04:45:30.667

2

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!

MD XF

Posted 2017-05-13T17:03:04.243

Reputation: 11 605

You could save one more byte by changing the logical AND (&&) comparison to a bitwise AND operation (&). – Cody Gray – 2017-05-14T11:11:18.183

1@CodyGray I don't think that would work if *s was odd. – Neil – 2017-05-14T11:36:20.563

2

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!

MD XF

Posted 2017-05-13T17:03:04.243

Reputation: 11 605

2Wouldn't it be T instead of R? – Okx – 2017-05-13T20:34:19.643

@Okx Wow, can't believe I missed that!! Thanks! – MD XF – 2017-05-13T20:34:39.643

1@MDXF, I like your shortC concept! I will be sending you some suggestions. – Johan du Toit – 2017-05-15T18:23:29.253

Yes, will chat soon. – Johan du Toit – 2017-05-15T18:32:37.917

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...) – RosLuP – 2017-05-20T09:20:41.987

@RosLuP Nope, I improved shortC so that opening parenthesis are usually unnecessary. Check out the GitHub repo for details about this language.

– MD XF – 2017-05-20T09:21:29.247

2

Python, 51 bytes

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

Try it online!

user69279

Posted 2017-05-13T17:03:04.243

Reputation:

1

Welcome to PPCG and nice first answer! This solution can be golfed by not using if-else statements like so: Try it online!

– user41805 – 2017-05-14T09:45:17.340

2

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

It Guy

Posted 2017-05-13T17:03:04.243

Reputation: 61

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 – 2018-03-29T09:32:30.573

2

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.

clap

Posted 2017-05-13T17:03:04.243

Reputation: 834

consistency @Svetlana it has to return a false value to keep with the false value returned by q – clap – 2017-05-20T22:29:07.520

2

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.

numbermaniac

Posted 2017-05-13T17:03:04.243

Reputation: 639

2

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

    Posted 2017-05-13T17:03:04.243

    Reputation: 535

    1You could save bytes by making this a lambda, so you wouldn't need the word return. – numbermaniac – 2017-05-20T02:09:09.410

    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 – 2017-05-20T10:10:24.773

    1Yeah, 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 – 2017-05-20T11:29:41.703

    This gives an IndexError when called on an empty string. Not sure if that's within the rules. – jqblz – 2017-06-20T04:32:49.337

    2

    Ruby, 16 17 bytes

    Outputs true or false. Now with fixed syntax error.

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

    Try it online!

    Value Ink

    Posted 2017-05-13T17:03:04.243

    Reputation: 10 608

    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 – 2017-05-20T01:44:57.980

    p !!(~/./&&~/#$&$/) works. – Ørjan Johansen – 2017-05-20T01:55:41.603

    @Ø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 – 2017-05-22T19:36:37.253

    1

    Python, 31 bytes

    lambda x:bool(x)and x[0]==x[-1]
    

    Erik the Outgolfer

    Posted 2017-05-13T17:03:04.243

    Reputation: 38 134

    You can eliminate the explicit call to bool and save 5 bytes: lambda x:x and x[0]==x[-1] – musicman523 – 2017-05-13T17:55:00.037

    @musicman523 It wouldn't follow the rules then. – Erik the Outgolfer – 2017-05-13T18:03:07.560

    My bad (see thread above) – musicman523 – 2017-05-14T08:00:19.513

    1

    J, 8 bytes

    1 byte thanks to Kritixi Lithos.

    1{.{.=|.
    

    Try it online!

    Leaky Nun

    Posted 2017-05-13T17:03:04.243

    Reputation: 45 011

    7 bytes: {:@{.@= – FrownyFrog – 2018-03-26T10:37:34.157

    1

    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!

    totallyhuman

    Posted 2017-05-13T17:03:04.243

    Reputation: 15 378

    You can use and instead of conditionals and save many bytes: lambda s:s and s[0]==s[-1] – musicman523 – 2017-05-13T17:57:20.723

    If I try to golf further, I'll end up copying the other answers. – totallyhuman – 2017-05-13T18:26:48.070

    @musicman523 that does not work for the empty string – Mr. Xcoder – 2017-05-13T18:31:33.757

    @Mr.Xcoder It would return the empty string, I thought this would be considered a falsey value since bool('') == False – musicman523 – 2017-05-13T20:38:26.250

    1@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 – 2017-05-14T07:56:35.073

    You could use a shorter false like 1>2. – manatwork – 2018-03-29T08:36:04.737

    1

    Standard ML - 52 54 bytes

    open String
    fn s=>s<>""andalso sub(s,0)=sub(s,size s-1)
    

    musicman523

    Posted 2017-05-13T17:03:04.243

    Reputation: 4 472

    This raises uncaught exception Subscript, you need size s-1. – Laikoni – 2017-05-13T17:51:36.380

    1

    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
    

    steenbergh

    Posted 2017-05-13T17:03:04.243

    Reputation: 7 772

    1

    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.

    aditsu quit because SE is EVIL

    Posted 2017-05-13T17:03:04.243

    Reputation: 22 326

    1

    Ruby, 22 20 bytes

    ->x{x[0]===x[-1]||p}
    

    canhascodez

    Posted 2017-05-13T17:03:04.243

    Reputation: 201

    1

    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.

    qoou

    Posted 2017-05-13T17:03:04.243

    Reputation: 711

    1

    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.

    Neil

    Posted 2017-05-13T17:03:04.243

    Reputation: 95 035

    1

    Perl 6,  18  17 bytes

    {?m/^(.)[.*$0]?$/}
    

    Test it

    {?/^(.)[.*$0]?$/}
    

    Test it

    Expanded:

    {  # bare block lambda with implicit parameter 「$_」
    
      ?        # Boolify the following
    
      /        # match implicitly against 「$_」
    
    
        ^      # beginning of string
    
        (.)    # character 「$0」
    
        [
    
          .*   # followed by any number of characters
          $0   # and itself
    
        ]?     # optionally (Str with a single char)
    
        $  # end of string
      /
    }
    

    Brad Gilbert b2gills

    Posted 2017-05-13T17:03:04.243

    Reputation: 12 713

    Save a byte: {?/$(/^./&&$/)$/}: matches a character at the start, then if true matches $/ before the end. { ? / $(/^./ && $/) $/ } – Phil H – 2018-03-27T11:21:30.960

    Or even just delete the m... – Phil H – 2018-03-27T11:22:23.997

    1

    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

    Johan du Toit

    Posted 2017-05-13T17:03:04.243

    Reputation: 1 524

    1

    Java 8, 29 bytes

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

    Port of @Neil's Retina answer.

    Try it here.

    Kevin Cruijssen

    Posted 2017-05-13T17:03:04.243

    Reputation: 67 575

    1

    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
    

    Riley

    Posted 2017-05-13T17:03:04.243

    Reputation: 11 345

    Some competition :) – James – 2017-05-15T20:56:54.060

    1

    Perl 5: 28 bytes

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

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

    Tom Tanner

    Posted 2017-05-13T17:03:04.243

    Reputation: 251

    1

    PowerShell, 42 bytes

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

    goric

    Posted 2017-05-13T17:03:04.243

    Reputation: 271

    1

    Brain-Flak, 55 bytes

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

    Try it online!

    James

    Posted 2017-05-13T17:03:04.243

    Reputation: 54 537

    I don't think this works for single character input or empty input.

    – Riley – 2017-05-15T21:00:24.870

    1

    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)
    

    Mego

    Posted 2017-05-13T17:03:04.243

    Reputation: 32 998

    This fails for an empty string. – Ørjan Johansen – 2017-05-16T00:39:43.700

    @ØrjanJohansen Fixed – Mego – 2017-05-16T01:07:03.373

    1

    Excel VBA, 52 48 40 38 37 36 34 Bytes

    Anonymous VBE immediate window function that takes input of type variant and expected type variant\String from cell [A1] on the ActiveSheet object and outputs boolean response to the VBE immediate window.

    ?[A1]<>""=([Left(A1)]=[Right(A1)])
    

    Taylor Scott

    Posted 2017-05-13T17:03:04.243

    Reputation: 6 709

    Fails on blank cell. Returns error message instead of falsey. – Engineer Toast – 2017-05-16T12:43:55.557

    @EngineerToast I have corrected for this, though it was more costly than I would have hoped – Taylor Scott – 2017-05-16T22:20:12.430

    1I never knew you could use bracketed addresses as a shorthand for the cell value from the active sheet. I learned a thing. Also, I think you can save 4 bytes with Left(a,1)=Right(a,1) instead of the Mids. Right? – Engineer Toast – 2017-05-17T12:17:29.403

    You are absolutely correct @EngineerToast, and on top of that it Left and Right do not return error on empty string input so I can drop the If statement! Thanks :) – Taylor Scott – 2017-05-21T16:25:55.840

    1

    Perl 5, 22+1 (-p flag)=23 bytes

    /^(.).*(.)/;$_=$1 eq$2
    

    Outputs 1 for truthy and an empty string for falsey.

    Chris

    Posted 2017-05-13T17:03:04.243

    Reputation: 1 313

    1

    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.

    theblitz

    Posted 2017-05-13T17:03:04.243

    Reputation: 1 201

    1

    Clojure: 21, 27 or 34 bytes

    depending on the handling of "" test case

    true for "aba" and "", false for "abc":

    #(=(first %)(last %))
    

    true for "aba", nil for "", false for "abc":

    #(first(map =(reverse %)%))
    

    true for "aba", nil for "" and "abc":

    #(or(first(map =(reverse %)%))nil)
    

    NikoNyrh

    Posted 2017-05-13T17:03:04.243

    Reputation: 2 361

    1This fails for the empty string. – Ørjan Johansen – 2017-05-18T00:18:57.677

    In comments it was discussed whether it makes sense to define the "correct" answer for an empty string. In Clojure first and last return nil (null) for empty sequences, and nil = nil. – NikoNyrh – 2017-05-18T12:35:57.830

    1The discussion ended with keeping the empty string test case as false, because so many answers already had adapted to it. – Ørjan Johansen – 2017-05-18T17:09:26.683

    1

    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.

    Phlarx

    Posted 2017-05-13T17:03:04.243

    Reputation: 1 366

    Uh! That's a lot of explanation! Thanks for that! :) – Arjun – 2017-05-19T16:26:08.563

    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 – 2017-05-19T16:29:35.233

    1

    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.

    Cyoce

    Posted 2017-05-13T17:03:04.243

    Reputation: 2 690

    1

    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)
    

    RosLuP

    Posted 2017-05-13T17:03:04.243

    Reputation: 3 036

    1

    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.

    pizzapants184

    Posted 2017-05-13T17:03:04.243

    Reputation: 3 174

    1

    Powershell, 30 bytes

    "$args"|%{!($_[0]-$_[-1]+!$_)}
    

    Try it online

    Andrei Odegov

    Posted 2017-05-13T17:03:04.243

    Reputation: 939

    1

    PowerShell, 25 Bytes

    ($a="$args")[0]-ceq$a[-1]
    

    gets the first char and last char, performed a case-sensitive comparison of them.

    colsw

    Posted 2017-05-13T17:03:04.243

    Reputation: 3 195

    1

    q/kdb+, 21 20 18 bytes

    Solution:

    {#:[x]&(1#x)~-1#x}
    

    Example:

    q){#:[x]&(1#x)~-1#x}"abc"
    0
    q){#:[x]&(1#x)~-1#x}"abca"
    1
    q){#:[x]&(1#x)~-1#x}""
    0
    

    Explanation:

    Take the first and last elements of the list, check for equality (return boolean 1 or 0), then check length of string, return the minimum of these two results.

    {                } / anonymous lambda function
                 -1#x  / take (#) 1 item from end of list
           (1#x)       / take (#) 1 item from start of list
                ~      / are they equal
     #:[x]             / count (#:) length of list x
          &            / minimum
    

    streetster

    Posted 2017-05-13T17:03:04.243

    Reputation: 3 635

    1

    Tcl, 34 bytes

    proc C s {regexp ^(.)(.*\\1)?$ $s}
    

    Try it online!

    sergiol

    Posted 2017-05-13T17:03:04.243

    Reputation: 3 055

    1

    Vim, 30 bytes

    :s/\v^(.)(.*\1)?$/1
    :s/^..\+/
    
    

    Leaves you with 1, if the string starts and ends with the same character, or nothing, if it doesn't.

    oktupol

    Posted 2017-05-13T17:03:04.243

    Reputation: 697

    1

    Julia 0.6, 29 bytes

    f(x)=x==""?false:x[1]==x[end]
    

    Try it online!

    niczky12

    Posted 2017-05-13T17:03:04.243

    Reputation: 301

    1

    Husk, 4 bytes

    Γ·=→
    

    Try it online!

    Takes a string as an argument to the program, returns 0 for falsy cases and 1 for truthy cases.

    Explanation:

    Γ is list deconstruction. The version I'm using (listN) takes a binary function and returns a function that takes a list. This new function returns the default type (0 in this case) for an empty string, and otherwise applies the given function to the head and tail of the string. The binary function I'm giving it is = (equality), composed on the second argument (·) with (last element of a list).

    Sophia Lechner

    Posted 2017-05-13T17:03:04.243

    Reputation: 1 200

    1

    SmileBASIC 3, 36 bytes

    In SmileBASIC, 0 is false and 1 (or nonzero) is true.

    LINPUT S$L=LEN(S$)?L&&S$[0]==S$[L-1]
    

    Explainer:

     LINPUT S$                'read line from console to string S$
     L=LEN(S$)                'store length of line in L
     ? L && S$[0] == S$[L-1]
    '| |          |
    '| |          \-----------first char equals last char
    '| \----------------------length is false if zero, && shortcuts
    '\------------------------print
    

    snail_

    Posted 2017-05-13T17:03:04.243

    Reputation: 1 982

    1

    Brachylog, 4 bytes

    h.&t
    

    Try it online!

    and

    Brachylog, 4 bytes

    h~t?
    

    Try it online!

    are both predicates which try to unify the first and last elements of the input, outputting through success or failure (which prints true. or false. when it's run as a program).

    Unrelated String

    Posted 2017-05-13T17:03:04.243

    Reputation: 5 300

    1

    PowerShell, 24 bytes

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

    Try it online!

    Gabriel Mills

    Posted 2017-05-13T17:03:04.243

    Reputation: 778

    0

    Golang, 27 bytes

    if n[0:1] == n[(len(n))-1:]
    

    Full Program

    package main
    import (
        "fmt"
    )
    func f(x string) string {
        if x[0:1] == x[(len(x))-1:] {
            return "Truthy"
        } else {
            return "Falsey"
        }
    }
    func main() {
        var n string
        fmt.Scanf("%q", &n)
        fmt.Printf("%q", f(n))
    }
    

    Try it online!

    ersinakyuz

    Posted 2017-05-13T17:03:04.243

    Reputation: 89

    0

    Cubix, 20 bytes

    @O0UA?n\.\1.1\2ntc?U
    

    Returns 0 for false and 1 for true.

    Cubified:

        @ O
        0 U
    A ? n \ . \ 1 .
    1 \ 2 n t c ? U
        . .
        . .
    

    explanation:

    A - read in input as chars; so input of abc has the stack -1,99,98,97
    ? - turn left if negative (empty string), right if positive
    if negative:
       0 - push 0
       U - left u-turn
       O - output as int
       @ - end program
    if positive:
    \ - reflect so we are moving to the right
    2 - push 2
    n - negate top of stack 
    t - pop top of stack, move that item from the bottom to the top; moves the last character to top of stack
    c - xor
    ? - turn right if positive, go straight if negative
    if 0:
       U - left U-turn
       1 - push 1
       \ - reflect so we point up
       O - output 1
       @ - end program
    if positive
       n - negate
       \ - reflect
       n - negate
       ? - righthand turn
       0 - push 0
       U - lefthand U-turn
       O - output
       @ - end program
    

    Try it online!

    Watch it online

    Giuseppe

    Posted 2017-05-13T17:03:04.243

    Reputation: 21 077

    0

    Tcl, 59 bytes

    proc C s {expr {[string in $s 0]==[string in $s e]&$s!=""}}
    

    Try it online!

    sergiol

    Posted 2017-05-13T17:03:04.243

    Reputation: 3 055

    0

    C (gcc), 45 bytes

    f(s,j)char*s;{for(j=*s;*s;s++);j=j&&j==*--s;}
    

    Try it online!

    Jonathan Frech

    Posted 2017-05-13T17:03:04.243

    Reputation: 6 681

    0

    SmileBASIC, 29 bytes

    DEF E S?S>""&&POP(S)==S[0]END
    

    Pretty simple, but it's important that the POP is done after the first character is checked, so it will work on 1 character long strings.

    12Me21

    Posted 2017-05-13T17:03:04.243

    Reputation: 6 110

    0

    ActionScript 2.0, 49 57bytes

    function a(b){trace(b!=""?b.substr(0,1)==b.slice(-1):0);}
    

    Old version (v) doesn't output false for "", but the new, longer version does.

    function a(b){trace(b.substr(0,1)==b.slice(-1));}
    

    I'm fairly sure this is the shortest way to do it, but...

    The semicolon can be removed and it'll still compile in JPEXS.

    This is a pretty simple function - if the argument is not "", output whether the (0, 1) substring of the argument (basically a way of getting the first character) is equal to the last character, obtained by slicing the string at its last character, otherwise 0. Tracing is shorter than returning.

    Jhynjhiruu Rekrap

    Posted 2017-05-13T17:03:04.243

    Reputation: 61

    What does this do for the empty string? – Ørjan Johansen – 2018-03-27T01:57:27.290

    Fixed. Now it checks for the empty string and returns 0. – Jhynjhiruu Rekrap – 2018-03-27T07:54:41.483

    0

    ><>, 11 bytes

    l?!<{:}=n;!
    

    Try it online!

    Takes input through the -s flag. You'll need to remove the flag for an empty input.

    How it works

    l?!<  Go right if there is input, left is there is none
        {:  If there is input, rotate the stack and dupe the first element
            This creates two copies of a one character input
          }=n;  Print if the last character is equal to the first
    l  If there is no input, push the length of the stack (0)
            n;!  Wrap around and print the 0
    

    Jo King

    Posted 2017-05-13T17:03:04.243

    Reputation: 38 234

    0

    jq, 23 characters

    (20 characters code + 3 characters command line option)

    .>""and.[:1]==.[-1:]
    

    Sample run:

    bash-4.4$ jq -R '.>""and.[:1]==.[-1:]' <<< $'10h01\nNothing\nAcccca\nwow!\nwow\nH\n'
    true
    false
    false
    false
    true
    true
    false
    

    Try it online!

    jq, 25 characters

    (22 characters code + 3 characters command line option)

    endswith(.[:1])and.>""
    

    Just to show that jq also has endswith() function. But unfortunately all strings are considered to end with empty string, so is not shorter. ☹

    manatwork

    Posted 2017-05-13T17:03:04.243

    Reputation: 17 865

    0

    GolfScript, 7 bytes

    )\(@=\;
    

    Try it online!

    Explanation

    )       # The last character
     \(     # And the first character
       @=\; # Are they equal
    

    user85052

    Posted 2017-05-13T17:03:04.243

    Reputation:

    0

    Burlesque, 6 bytes

    l_-]==
    

    Try it online!

    l_ # Non-destructive tail, leaving the rest of the string on top of the stack
    -] # Destructive head
    == # Equal
    

    DeathIncarnate

    Posted 2017-05-13T17:03:04.243

    Reputation: 916