Une «chaîne paire» est une chaîne dans laquelle la parité des valeurs ASCII des caractères est toujours alternative. Par exemple, la chaîne EvenSt-ring$!
est une chaîne paire car les valeurs ASCII des caractères sont les suivantes:
69 118 101 110 83 116 45 114 105 110 103 36 33
Et les parités de ces nombres sont:
Odd Even Odd Even Odd Even Odd Even Odd Even Odd Even Odd
Ce qui alterne tout le chemin. Cependant, une chaîne comme Hello world!
n'est pas une chaîne paire car les valeurs ASCII sont les suivantes:
72 101 108 108 111 32 87 111 114 108 100 33
Et les parités sont:
Even Odd Even Even Odd Even Odd Odd Even Even Even Odd
Ce qui n'est clairement pas toujours en alternance.
Le défi
Vous devez écrire un programme complet ou une fonction qui accepte une chaîne en entrée et génère une valeur de vérité si la chaîne est paire, et une valeur falsy sinon. Vous pouvez effectuer vos entrées et vos sorties dans n’importe quel format raisonnable, et vous pouvez supposer que l’entrée aura uniquement l’ impression ASCII (plage 32-127). Vous n'êtes pas obligé de gérer une entrée vide.
Exemples
Voici quelques exemples de chaînes égales:
#define
EvenSt-ring$!
long
abcdABCD
3.141
~
0123456789
C ode - g ol!f
HatchingLobstersVexinglyPopulateJuvenileFoxglove
Et tous ces exemples ne sont même pas des chaînes:
Hello World
PPCG
3.1415
babbage
Code-golf
Standard loopholes apply
Shortest answer in bytes wins
Happy golfing!
Vous pouvez également utiliser cette solution non-golfée pour tester des chaînes si vous êtes curieux de connaître un certain cas de test.
lno
.Réponses:
MATL ,
43 octetsMerci à Emigna d’ avoir économisé un octet et merci àLuis Mendo for fixing some bugs. Code:
Explication:
Essayez-le en ligne!
la source
A
.A
out thanks to the way MATL'sif
works.2\
byo
. And the code will look very... imperative:-)4
is still regular4
...05AB1E,
54 bytesSaved 1 byte thanks to Adnan.
Try it online!
Explanation
la source
Ç¥ÉP
:)Jelly,
754 bytesSaved 2 bytes using the deltas idea from @Steven H.
Saved 1 byte thanks to @Lynn.
Try it online! or Verify all test cases.
Explanation
la source
%2
→Ḃ
mod
.Python 2, 54 Bytes
la source
Mathematica,
5044 bytesThe current version is basically all Martin Ender's virtuosity.
Returns
True
orFalse
. Nothing too clever: takes the mod-2 sum of each pair of consecutive ASCII codes, and checks that 0 is never obtained.Old version:
la source
JavaScript (ES6),
605046 bytesI tried recursion, but at 51 bytes, it doesn't seem to be quite worth it:
Test snippet
Show code snippet
la source
s=>[...Buffer(s)].every(c=>p-(p=c&1),p=2)
Brain-Flak,
13811411284 + 3 = 87 bytesThanks to @Riley for help golfing.
This program treats empty input as a noneven string.
Try it online!
Explanation (outdated)
Shifts the input from the left stack to the right while modding by 2. Finds the difference between each adjacent character until all have been checked or one of the differences is equal to zero (which would only occur in a noneven string). If the loop terminated due to a noneven string then switch back to the left stack and pop the value remaining on it. Otherwise, stay on the right stack and pop the zero above the 1 remaining on the stack.
la source
([]){{}
->{
and remove([])
from just before the close of the first loop.{({}(())){({}[()]<(()[{}])>)}{}({}<>)<>}<>
(42 bytes). This was derived from your original modulus. To make it work with your program an additional +1 nilad needs to be added:{({}(())){({}[()]<(()[{}])>)}{}({}()<>)<>}<>
R,
4135 bytesEDIT: Saved a few bytes thanks to @JDL by using
diff
instead ofrle
.Explanation
readline()
read input.utf8ToInt()%%2
convert to ascii values and mod 2 (store as R-vector)all(rle()==1)
run length encoding of to find runs. All runs should be equal to one or smaller than 2 since no runs cant be negative or 0 (saves one byte instead of==
).la source
prod(...)
rather thanall(... == 1)
saves a few chars.>1
?all
was entirely zeroes and ones.rle
and usingdiff
:all(diff(utf8ToInt(readline())%%2))
(we get a warning, but I don't think that's disallowed)all(numeric(0))
which isTRUE
, the desired answer for a length one string. (I tested, if it matters, against R-3.3.1)Pyth (fork), 9 bytes
No Try It Online link because the fork does not have its own version in the online interpreters.
Explanation:
la source
Brachylog, 17 bytes
Try it online!
Explanation
la source
Java 8,
77767257 bytes-4 bytes thanks to @Geobits.
Explanation:
Try it online.
la source
boolean
here (I know, it sucks). The best I could get this that way (72) is by using a flag-int like:boolean c(char[]a){int i=3,b=1;for(int c:a)b=i==(i=c%2)?0:b;return b>0;}
Brain-Flak
155 151 141121Includes +3 for -a
Saved 30 bytes thanks to 1000000000
Output:
truthy: 1
falsy: 0 on top of the stack
Try it online! (truthy)
Try it online! (falsy)
Better explanation coming later (if I can remember how it works after a few hours...)
la source
Starry, 85 bytes
Try it online!
Note that since a Starry program has no way of telling when an input of arbitrary length ends, this program uses a trailing newline in the input to mark the end of the string. If you get a cryptic error message about and undefined method
ord
fornil:NilClass
then the input is missing a trailing newline.Explanation
The basic strategy that the program employs is it reads the characters one by one from input and if they are not a newline (character 10) it mods they ASCII value of the character by 2 and finds the difference between it and the previously read character. If the difference is zero the program terminates and prints
0
(falsey). Otherwise the program loops back and does the process over again. If the program reads a newline it terminates and prints10
(truthy).Annotated Program
la source
Perl, 24 + 1 (
-p
) = 25 bytes-4 bytes thanks to @Ton Hospel !
Needs
-p
flag. Outputs 1 is the string is even, nothing otherwise. For instance :Explanations : replaces each character by its value mod 2 (so the string contains only 0s and 1s after that). Then search for two following 1 or 0 : if it finds some, then the string isn't even, otherwise it is.
la source
s/./$&&v1/eg;$_=!/(.)\1/
. PS(ord$&)%2
could have been written as1&ord$&
v1
?\x01
isn'tJ, 15 bytes
Usage
Explanation
la source
Vim, 38 bytes
qqs<C-R>=char2nr(@")%2<CR><Esc>l@qq@q:g/00\|11/d<CR>
Assumes input string in buffer, and empty
"q
. Outputs binary nonsense if true, nothing if false.s<C-R>=char2nr(@")%2<CR>
: Replaces a character with 1 if odd, 0 if even. The macro this is in just does this to every character in the line (no matter how long it is).:g/00\|11/d<CR>
: Deletes the line if 2 consecutive "bits" have the same value. Faster than a back-reference.Normally, in vimgolf, when you use an expression function inside a macro, you're supposed to do the macro itself on the expression register and use some trickery to tab-complete. That's more difficult this time. I may find a way to shorten that later.
la source
Retina, 39 bytes
Byte count assumes ISO 8859-1 encoding.
Outputs
1
for truthy and0
for falsy.Try it online! (The first line enables a linefeed-separated test suite.)
Explanation
Inspired by a answer of mbomb007's I recently developed a reasonably short
ord()
implementation in Retina. This is largely based on that, although I was able to make a few simplifications since I don't need a decimal result in since I only need to support printable ASCII (and I only care about the parity of the result, so ending up with an arbitrary offset is fine, too).Stage 1: Split
This simply splits the input into its individual characters by splitting it around the empty match and dropping the empty results at the beginning and end with
_
.Stage 2: Replace
The
%{
tells Retina a) that this stage and the next should be run in a loop until the string stops changing through a full iteration, and that these two stages should be applied to each line (i.e each character) of the input separately.The stage itself is the standard technique for duplicating the first character of the input. We match the empty string (but only look at the first two matches) and insert the prefix of that match. The prefix of the first match (at the beginning of the string) is empty, so this doesn't do anything, and the prefix of the second match is the first character, which is therefore duplicated.
Stage 3: Transliterate
}
indicates the end of the loop. The stage itself is a transliteration.01
indicates that it should only be applied to the first character of the string.p
is shorthand for all printable ASCII characters and_
means "delete". So if we expand this, the transliteration does the following transformation:So spaces are deleted and all other characters are decremented. That means, these two stages together will create a character range from space to the given character (because they'll repeatedly duplicate and decrement the first character until it becomes a space at which point the duplication and deletion cancel).
The length of this range can be used to determine the parity of the character.
Stage 4: Replace
We simply drop all pairs of characters. This clears even-length lines and reduces odd-length lines to a single character (the input character, in fact, but that doesn't really matter).
Stage 5: Match
It's easier to find inputs which aren't even, so we count the number of matches of either two successive empty lines or two successive non-empty lines. We should get
0
for even inputs and something non-zero otherwise.Stage 6: Match
All that's left is to invert the result, which we do by counting the number of matches of this regex, which checks that the input starts with a
0
. This is only possible if the result of the first stage was0
.la source
Clojure, 59 bytes
Generates all sequential pairs from string
n
and checks if every pair sum is odd. If a sequence of ints is considered a reasonable format then it's 50 bytes.See it online : https://ideone.com/USeSnk
la source
Julia,
5553 BytesExplained
Map chars to 0|1 and check if the resulting string contains "00" or "11", which makes the string not alternating.
la source
Python, 52 bytes
A recursive function. Produces 1 (or True) for even strings, 0 for odd ones. Multiplies the parity of the difference of the first two characters by the recursive value on the remainder. A single-character string gives True, as checked by it equaling its first character. This assumes the input is non-empty; else, one more byte is needed for
s==s[:1]
orlen(s)<2
.Python 2, 52 bytes
Alternatively, an iterative solution. Iterates over the input characters, storing the current and previous character values mod 2. Multiplies the running product by the difference, which because 0 (Falsey) only when two consecutive parities are equal.
The "previous" value is initialized to 2 (or any value not 0 or 1) so that the first character never matches parity with the fictional previous character.
Python, 42 bytes, outputs via exit code
Outputs via exit code. Terminates with a ZeroDivisionError when two consecutive characters have the same parities, otherwise terminates cleanly.
la source
Haskell,
4240 bytesUsage example:
all odd.(zipWith(-)=<<tail).map fromEnum $ "long"
->True
.How it works:
Edit: @xnor saved two bytes. Thanks!
la source
all odd.(zipWith(-)=<<tail).map fromEnum
.Mathematica,
4140 Bytes-1 character, thanks to Martin Ender
la source
C, 52 bytes
Compares the parity of first 2 characters, recursively moving through the string until it finds 2 characters with the same parity or the string with the length of 1 (
s[1] == 0
).Code with some of the test cases
la source
f(char*s){s=s[1]?(*s-s[1])%2?f(s+1):0:1;}
you don't need the int, return or [0]*++s
instead of the seconds[1]
you can changef(s+1)
tof(s)
. that plus my previous comment bring the total down to 39; I should also add that removingreturn
makes it not work on ideone, but it still works with gcc on windowsf(char*s){s=s[1]?(*s-*++s)%2&&f(s):1;}
I'd go on but it's 5 am and I have wake up in 3 hours lmaoPyke, 8 bytes
Try it here!
la source
C#, 69 bytes
Full program with test cases:
la source
PHP, 69 Bytes
solution with Regex 81 Bytes
la source
PowerShell v2+, 47 bytes
(Can't quite catch PowerShell's usual competitors ...)
Takes input
$args[0]
as a string, casts it as achar
-array, loops through it|%{...}
, each iteration placing the modulo on the pipeline (with implicit[char]
to[int]
conversion). Those are encapsulated in parens and-join
ed into a string, which is fed into the left-hand of the-notmatch
operator, checking against00
or11
(i.e., returnsTrue
iff the0
s and1
s alternate). That Boolean result is left on the pipeline and output is implicit.Test Cases
la source
><>,
2927 bytesOutputs 1 if the word is even, 0 if the word is odd.
You can try it online.
Edit : saved two bytes thanks to Martin Ender
la source
Perl 6,
4726 bytesExpanded:
la source
Scala, 54 bytes
I'm sure this can be improved.
la source