L'inizio equivale alla fine?


36

L'obiettivo

In questa sfida, il tuo compito è quello di scrivere un programma o una funzione che accetta una stringa e genera un valore di verità o falsità in base al fatto che il primo carattere e l'ultimo carattere della stringa di input siano uguali.

Ingresso

È possibile accettare input in qualsiasi modo ragionevole. Tuttavia, supponendo che l'input sia presente in una variabile predefinita non è consentito. È consentito leggere da un file, console, riga di comando, campo di input, ecc. O accettare input come argomento di funzione.

Produzione

È possibile eseguire l'output in qualsiasi formato ragionevole, ad eccezione dell'assegnazione del risultato a una variabile. returnÈ consentito scrivere su un file, console, riga di comando, casella modale, istruzioni di funzione ecc.

Regole aggiuntive

  • L'input può essere anche String vuoto, per il quale è necessario restituire un valore false.

  • Le stringhe di input a carattere singolo dovrebbero avere un risultato veritiero.

  • Il tuo programma dovrebbe fare distinzione tra maiuscole e minuscole. helloHdovrebbe generare un valore false.

  • Puoi avere solo un singolo valore di Verità e un singolo valore di Falsey. Ad esempio, l'output falseper una stringa di input e 0per un'altra stringa di input come valori Falsey non è consentito.

  • Non sono ammesse scappatoie standard .

Casi test

Input    ->    Output

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

Questo è , quindi vince il codice più corto in byte!


Quali caratteri possono apparire nell'input? ASCII stampabile?
Martin Ender,

@MartinEnder ASCII stampabile. Anche se non penso che importi molto.
Arjun,

Certo che importa. Alcune lingue non possono elaborare caratteri non ASCII o byte nulli e in una regex posso abbinare qualsiasi carattere ASCII stampabile con ., ma non corrisponderebbe agli avanzamenti di riga. In generale, se ti trovi ad usare il tag stringa , specifica esattamente quali caratteri possono apparire nell'input.
Martin Ender,

@MartinEnder Okay. Ci penseremo in futuro.
Arjun,

Caso di prova suggerito:AbAb => false
caird coinheringaahing

Risposte:



17

Python 3 , 23 byte

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

L'output avviene tramite il codice di uscita, quindi 0 (esito positivo) è veritiero e 1 (esito negativo) è errato. Se questo è accettabile, è possibile salvare un byte.

Provalo online!

Come funziona

Prima di tutto, se s è una stringa vuota, s[0]genererà IndexError , causando il fallimento del programma.

Per non vuoti s , se il primo e l'ultimo carattere sono uguali, s[0]!=s[-1]valuterà a False , quindi il programma termina in modo pulito e immediatamente.

Infine, se i personaggi sono diversi, s[0]!=s[-1]valuteranno True , causando l'esecuzione del compagno s[-1]<e. Poiché e non è definito, viene generato un NameError .

Se non si desidera la retrocompatibilità con Python 2,

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

funziona anche, poiché il confronto di una stringa con un numero intero genera un TypeError .


Salva 1 byte con lambda
OldBunny2800

1
Sì, una funzione regolare salverebbe anche un byte. Mentre l'output tramite il codice di uscita è un consenso stabilito, non errore / errore per una funzione non è però. Ho collegato alla proposta nella mia risposta.
Dennis,

Che dire dell'utilizzo di Python REPL?
OldBunny2800

Non penso che aiuti. Non è ancora un codice di uscita.
Dennis,

9

JavaScript, 19 byte

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

Wow. Non sapevo nemmeno che esistesse un endsWithmetodo per l'oggetto String. Bello! :)
Arjun,

Come mi sono dimenticato endsWith()?! Ho aspettato l'opportunità di usarlo.
Shaggy,

7

Mathematica, 15 byte

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

Accetta una serie di caratteri. Genera errori quando l'input è vuoto ma può essere ignorato.


4
Bel lavoro individuando il fatto che ===gestisce il caso vuoto :)
Greg Martin,



7

C ++, 39 byte

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

Programmi completi:

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

Provalo online


1
Non sono il migliore in C ++ (in genere uso C), ma potresti cambiare le istanze di s[0]in *sper salvare due byte ciascuna?
MD XF,

1
@MDXF, che funzionerà solo con array di tipo C.
Johan du Toit,

6

Brachylog , 4 byte

h~t?

Provalo online!

Spiegazione

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

1
Ho davvero bisogno di andare in giro per implementare quelle variabili di vincolo per l'input; ciò significherebbe che saremmo in grado di farlo in due.

6

Java, 81 77 byte

  • -4 byte, grazie @KevinCruijssen

Prova online

boolean f(String s){int l=s.length();return l>0&&s.charAt(l-1)==s.charAt(0);}
  • Restituisce truese sono uguali, altrimenti false, falseper stringa vuota

Versione array, 60 byte

boolean f(char[]s){int l=s.length;return l>0&&s[0]==s[l-1];}

Perché lungo invece di int?
corvus_192

@corvus_192 a unicode character can be 1-6 bytes.
Khaled.K

The difference between two chars can be at most Charcter.MAX_VALUE - Character.MIN_VALUE, which is 65535
corvus_192

@corvus_192 I see, I've fixed it now
Khaled.K

1
@KevinCruijssen For the last, s.charAt(l-1)==s.charAt(0) would save two bytes.
JollyJoker


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.


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.

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


Very clever approach!
Luis Mendo

Also 5 bytes: 5L)d~.
Sanchises

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

1
(of course, you could do tn?&=PO)}F to deal with empty input; not sure if there is a more efficient way)
Sanchises


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.


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

@Adám Thank you for helping me see the mistake in my explanation.
Kritixi Lithos

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

The first argument reversedThe right argument reversed
Adám

You may also want to explain why this works on empty strings.
Adám

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

1
You can shave off 9 chars using s.endsWith(""+s.charAt(0)) instead of s.charAt(0)==s.charAt(s.length()-1)
SpaceBison

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

1
@JollyJoker that does not work: try feeding new String() into the lambda. It will throw an exception. Reference semantics do not work here.

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

4

Ruby, 26 24 bytes

Saved two bytes thanks to @philomory!

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

First post on codegolf -))


1
Welcome to PPCG!
Martin Ender

1
Welcome to PPCG! Nice first golf. Good luck for future!
Arjun

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

3

PHP>=7.1, 23 Bytes

prints 1 for equal and nothing if the character is different

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

3

Swift, 57 bytes

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

Edited the code.
Leena

Welcome to PPCG! Is the space after a.last necessary?
HyperNeutrino

Either I can add brackets around a.last or I can add space after a.last
Leena

3

C#, 38 30 bytes

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

Saved 8 bytes thanks to @raznagul.


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

@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

@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

@raznagul Oh yeah... brain fart.
TheLethalCoder

Perhaps its a bit late but you can save 5 bytes if you use s.Last() instead of s[s.Length-1]
Bojan B

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

2
You can remove one set of parentheses with rev(y<-el(strsplit(x,"")))==y.
Nitrodon

1
also unnamed functions are acceptable, so you can remove the f=
MickyT

1
and charToRaw can be used to split the string for comparison function(x)x>""&&rev(y<-charToRaw(x))==y
MickyT

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

Hello! Welcome to PPCG! Nice first golf! Good luck for future! :)
Arjun

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


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

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

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

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

You can replace charToRaw with utf8ToInt to produce NAs when the string is empty.
niczky12

You can also remove the curly braces {} around the function body.
Giuseppe

I think (y==rev(y))[1] is shorter by a byte
Giuseppe

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

@ØrjanJohansen thanks for your comment, so "ab" should not give FALSE?
Riccardo Camon

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.


2

GNU grep, 12 bytes

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

Run in extended or PCRE mode.

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


Does this handle the empty string case?
clap

@ConfusedMr_C Yep, empty string ⇒ code 1.
eush77

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.



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.


1
Suggest if instead of and and (mismatch(reverse s)s) instead of (mismatch s(reverse s))
ceilingcat

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

1
I believe the rule is that you can use flags/options, but you need to include them in the byte count.
Ørjan Johansen
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.