36
\$\begingroup\$

An 'Even string' is any string where the parity of the ASCII values of the characters is always alternating. For example, the string EvenSt-ring$! is an even-string because the ASCII values of the characters are:

69 118 101 110 83 116 45 114 105 110 103 36 33

And the parities of these numbers are:

Odd Even Odd Even Odd Even Odd Even Odd Even Odd Even Odd

Which is alternating the whole way. However, a string like Hello world! is not an even string because the ASCII values are:

72 101 108 108 111 32 87 111 114 108 100 33

And the parities are:

Even Odd Even Even Odd Even Odd Odd Even Even Even Odd

Which is clearly not always alternating.

The challenge

You must write either a full program or a function that accepts a string for input and outputs a truthy value if the string is even, and a falsy value otherwise. You can take your input and output in any reasonable format, and you can assume that the input will only have printable ASCII (the 32-127 range). You do not have to handle empty input.

Examples

Here are some examples of even strings:

#define
EvenSt-ring$!
long
abcdABCD
3.141
~
0123456789
C ode - g ol!f
HatchingLobstersVexinglyPopulateJuvenileFoxglove

And all of these examples are not even strings:

Hello World
PPCG
3.1415
babbage
Code-golf
Standard loopholes apply
Shortest answer in bytes wins
Happy golfing!

You may also use this ungolfed solution to test any strings if you're curious about a certain test-case.

\$\endgroup\$
  • \$\begingroup\$ this may be slightly more readable \$\endgroup\$ – ASCII-only Oct 13 '16 at 8:56
  • 1
    \$\begingroup\$ Can the input be length 1? Empty? \$\endgroup\$ – xnor Oct 13 '16 at 8:59
  • 2
    \$\begingroup\$ @xnor There's a length-1 example in the test cases, but empty input is a good question. \$\endgroup\$ – Martin Ender Oct 13 '16 at 9:04
  • \$\begingroup\$ Add another uneven string as a test case: lno. \$\endgroup\$ – adrianmp Oct 13 '16 at 10:23
  • 4
    \$\begingroup\$ Any bonus points for program itself being an even string? \$\endgroup\$ – Daerdemandt Oct 13 '16 at 19:14

42 Answers 42

1 2
1
\$\begingroup\$

Node.js (ES6), 45 44 bytes

s=>![...Buffer(s)].some((b,c,d)=>b+c-d[0]&1)

The Buffer object saved me alot of trouble over charCodeAt().

Also felt like including my attempts via JavaScript (ES6), though they aren't as short as ETHproduction's:

a=>![...a].some((b,c,d)=>b.charCodeAt()+c-d[0]&1) // 49 bytes
a=>!/(.),\1/.test([...a].map(b=>b.charCodeAt()&1)) // 50 bytes
a=>new Set([...a].map((b,i)=>b.charCodeAt()+i&1)).size<2 // 56 bytes

The first in the JavaScript (ES6) equivalent of what I went with in Node.js. The second was an attempt to use regex to simplify the pattern matching (45 bytes in Node.js). The third was an attempt to use Set's ability to determine unique values, combined with math that made valid arrays be either all 1's or 0's (51 bytes in Node.js).

\$\endgroup\$
1
\$\begingroup\$

C, 54 bytes

int c,p=*s^1,r=1;while(c=*s++){r&=p^c;p=c;}return r&1;

An xor of previous and current chars equal to xxxxxxx1 indicates a difference in parity. ANDing the results of every pair of chars in the string computes the string parity. A zero length string returns true.

\$\endgroup\$
1
\$\begingroup\$

Ruby, 41 30 (+1) bytes

p gsub(/./){$&.ord%2}!~/(.)\1/

Call this from the command line with the -n flag, like so:

ruby -ne 'p gsub(/./){$&.ord%2}!~/(.)\1/'

Replaces each character with the parity of its ASCII value and then compares to a regex. If even, the =~ comparison will return the index of the first match (i.e. 0), which is a truthy value in Ruby; if not even, the comparison will return nil.

Thanks to Jordan for the improvements!

\$\endgroup\$
  • \$\begingroup\$ You can save 6 bytes by replacing =~/^0?(10)*1?$/ with !~/(.)\1/ (or !~/00|11/). \$\endgroup\$ – Jordan Oct 13 '16 at 19:23
  • \$\begingroup\$ You can get it down to 30 + 1 bytes with the -n flag and input on stdin: ruby -ne 'p gsub(/./){$&.ord%2}!~/(.)\1/'. \$\endgroup\$ – Jordan Oct 13 '16 at 19:29
1
\$\begingroup\$

Attache, 17 bytes

All@Odd@Delta@Ord

Try it online!

Checks if All of the Deltas are Odd.

Alternatives

19 bytes: All##Odd''Even##Ord

26 bytes: All##Odd@Sum=>Slices&2@Ord

\$\endgroup\$
0
\$\begingroup\$

Groovy, 33 30 Bytes

{(int)(it.getChars().sum())%2}

Basically collects the chars in the string into an array as their values modulo 2, sums them, then modulos the answer. In groovy a 0 is false and a 1 is a true. 0 for odd (false), 1 for true (even). This also implicitly handles empty input...

Try it: https://groovyconsole.appspot.com/script/5132426728701952

-2 Bytes if I can output an odd number if odd, even if even.

\$\endgroup\$
0
\$\begingroup\$

Python 3, 65 Bytes

l=p=print
for i in input():
    c=ord(i)%2
    if l==c:
        p(1>2)
        break
    l=c
else: p(1<2)
\$\endgroup\$
  • \$\begingroup\$ 1 and 0 are truthy and falsey (respectively) in Python, so you could print those instead of 1>2 and 1<2. Additionally, I count 92 bytes (interpreting the indents as tabs), and lots of whitespace that could be removed. \$\endgroup\$ – Mego Oct 13 '16 at 23:16
0
\$\begingroup\$

C#, 55 bytes

s=>{var f=1;for(;0<*++s;)f&=(*--s+*++s)%2;return 0<f;};

For all the dangerous golfers out there.

/*unsafe delegate bool Function(char* s);*/ // Function signature
/*unsafe Function Lambda = */ s => 
{
    var f = 1;                              // Output var, initialized to true
    for (; 0 < *++s;)                       // Enumerate string, starting from the 2nd char
         f &= (*--s + *++s) % 2;            // Bitwise AND whether previous and current
                                            // chars are alternating because 
                                            // even+odd = odd,
                                            // even+even = odd+odd = even.
    return 0 < f;                           // Cast int to bool
};
\$\endgroup\$
0
\$\begingroup\$

MATLAB, 18 bytes

@(s)mod(diff(s),2)

This returns

f=@(s)mod(diff(s),2)
f('PPCG')
ans =
     0     1     0
f('#define')
ans =
     1     1     1     1     1     1

In MATLAB, if x is a vector, then if x is equivalent to if all(x). According to this Meta post, it's enough to return x.

\$\endgroup\$
0
\$\begingroup\$

Racket 131 bytes

(let p((l (map even?(map char->integer(string->list s)))))(cond[
(= 1(length l))#t][(equal?(car l)(second l))#f][else(p(cdr l))]))

Ungolfed:

(define (f s)
    (let loop ((lst (map even? (map char->integer(string->list s)))))
      (cond
        [(= 1 (length lst)) #t]
        [(equal? (first lst) (second lst)) #f]
        [else (loop (rest lst))]
        )))

Testing:

(f "EvenSt-ring$!")
(f "#define")
(f "abcdABCD")
(f "babbage")
(f "Code-golf")
(f "PPCG")

Output:

#t
#t
#t
#f
#f
#f
\$\endgroup\$
0
\$\begingroup\$

Clean, 55 bytes

\x->all(\(a,b)->(toInt a-toInt b)rem 2>0)(zip2 x(tl x))
\$\endgroup\$
0
\$\begingroup\$

APL, 26 or 25 bytes

{~1∊↑(2/¨0 1)⍷¨2⍴⊂2|⍵}⎕UCS

One byte can be saved if ⎕IO is 0: {~1∊↑(2/¨⍳2)⍷¨2⍴⊂2|⍵}⎕UCS

The dyadic function returns 1 if the string is even, 0 otherwise.

\$\endgroup\$
0
\$\begingroup\$

Brain-Flak, 60 bytes

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

Try it online!

-a no longer costs 3 bytes, so this is a 24-byte improvement over 0 ''s answer. Output is 0 for falsy and 1\n0 for truthy.

The general idea is to calculate the parity of sums of adjacent characters until an even sum is reached. If the string is alternating, the stopping condition will occur after reaching the implicit zeroes below the stack. It thus suffices to check whether the next character is a null.

\$\endgroup\$
1 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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