EvenSt-ring C ode - g ol!f

36

1

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.

James

Posted 2016-10-13T05:42:44.623

Reputation: 54 537

this may be slightly more readable – ASCII-only – 2016-10-13T08:56:16.877

1Can the input be length 1? Empty? – xnor – 2016-10-13T08:59:19.923

2@xnor There's a length-1 example in the test cases, but empty input is a good question. – Martin Ender – 2016-10-13T09:04:57.350

Add another uneven string as a test case: lno. – adrianmp – 2016-10-13T10:23:21.940

@xnor The input may be length 1 (which is always even), but empty inputs may result in undefined behavior. I have added that clarification. – James – 2016-10-13T17:14:32.470

4Any bonus points for program itself being an even string? – Daerdemandt – 2016-10-13T19:14:36.813

@Daerdemandt I thought that's what this challenge was going to be when I first read it – Luigi – 2016-10-14T14:10:12.140

Answers

20

MATL, 4 3 bytes

Thanks to Emigna for saving a byte and thanks to Luis Mendo for fixing some bugs. Code:

doA

Explanation:

d     # Difference between the characters
 o    # Mod 2
  A   # Matlab style all

Try it online!

Adnan

Posted 2016-10-13T05:42:44.623

Reputation: 41 965

1I think a list of 1's is true in MATL, so you should be able to remove the A. – Emigna – 2016-10-13T09:34:02.240

1

See for example this post, stating so :)

– Emigna – 2016-10-13T09:54:52.207

@Emigna Thanks :). There has been some discussion about this, so I'm not sure if it is entirely valid. – Adnan – 2016-10-13T10:12:10.200

3

See this Meta question. The highest voted answer would allow for leaving the A out thanks to the way MATL's if works.

– Sanchises – 2016-10-13T10:13:25.163

...and we have a WINNER!!! – Erik the Outgolfer – 2016-10-13T12:04:09.753

4You can also replace 2\ by o. And the code will look very... imperative:-) – Luis Mendo – 2016-10-13T13:10:54.800

6Crossed out 4 is still regular 4... – AdmBorkBork – 2016-10-13T13:15:08.563

@Adnan However, you do need a final A to cover the one-char input (now that gives empty output, which is falsy). So again 3 bytes :-) – Luis Mendo – 2016-10-13T13:25:31.950

1@LuisMendo Thanks! It's really nice to have character arithmetic, I should probably implement that in osabie sometime :p. – Adnan – 2016-10-13T17:25:23.060

17

05AB1E, 5 4 bytes

Saved 1 byte thanks to Adnan.

Ç¥ÉP

Try it online!

Explanation

Ç       # convert to ascii values 
 ¥      # compute delta's
  É     # mod by 2
   P    # product

Emigna

Posted 2016-10-13T05:42:44.623

Reputation: 50 798

I believe this also works: Ç¥ÉP :) – Adnan – 2016-10-13T08:56:37.820

@Adnan: Lol, of course! Thanks! :) – Emigna – 2016-10-13T09:08:30.713

13

Jelly, 7 5 4 bytes

OIḂẠ

Saved 2 bytes using the deltas idea from @Steven H.

Saved 1 byte thanks to @Lynn.

Try it online! or Verify all test cases.

Explanation

OIḂẠ  Input: string S
O     Ordinal
 I    Increments
  Ḃ   Mod 2
   Ạ  All, 0 if it contains a falsey value, else 1

miles

Posted 2016-10-13T05:42:44.623

Reputation: 15 654

I had come up with the same Jelly answer independently, kudos – Steven H. – 2016-10-13T06:04:08.373

1

You can save one byte: %2

– Lynn – 2016-10-13T11:22:57.700

@Lynn Thanks, I felt like there was a builtin for mod 2, but I couldn't find it, was searching using mod. – miles – 2016-10-13T19:30:11.077

8

Python 2, 54 Bytes

lambda s:all((ord(x)-ord(y))%2for x,y in zip(s,s[1:]))

Karl Napf

Posted 2016-10-13T05:42:44.623

Reputation: 4 131

7

Mathematica, 50 44 bytes

The current version is basically all Martin Ender's virtuosity.

Differences@ToCharacterCode@#~Mod~2~FreeQ~0&

Returns True or False. Nothing too clever: takes the mod-2 sum of each pair of consecutive ASCII codes, and checks that 0 is never obtained.

Old version:

Union@Mod[Most[a=ToCharacterCode@#]+Rest@a,2]=={1}&

Greg Martin

Posted 2016-10-13T05:42:44.623

Reputation: 13 940

6

R, 41 35 bytes

EDIT: Saved a few bytes thanks to @JDL by using diff instead of rle.

all(diff(utf8ToInt(readline())%%2))

all(rle(utf8ToInt(readline())%%2)[[1]]<2)

Explanation

  1. readline() read input.
  2. utf8ToInt()%%2 convert to ascii values and mod 2 (store as R-vector)
  3. 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 ==).

Billywob

Posted 2016-10-13T05:42:44.623

Reputation: 3 363

I think using prod(...) rather than all(... == 1) saves a few chars. – JDL – 2016-10-13T10:27:12.540

1@JDL Not sure what you mean. Wouldn't this always return something >1? – Billywob – 2016-10-13T12:28:50.933

Sorry, I confused your solution with the method of another one. For some reason I thought the thing inside all was entirely zeroes and ones. – JDL – 2016-10-13T12:44:45.570

1I think we can save more actually by ditching rle and using diff: all(diff(utf8ToInt(readline())%%2)) (we get a warning, but I don't think that's disallowed) – JDL – 2016-10-13T12:54:31.950

I think it does; with a length one string, it boils down to all(numeric(0)) which is TRUE, the desired answer for a length one string. (I tested, if it matters, against R-3.3.1) – JDL – 2016-10-13T13:05:40.273

6

JavaScript (ES6), 60 50 46 bytes

s=>[...s].every(c=>p-(p=c.charCodeAt()%2),p=2)

I tried recursion, but at 51 bytes, it doesn't seem to be quite worth it:

f=([c,...s],p=2)=>c?p-(p=c.charCodeAt()%2)&f(s,p):1

Test snippet

f=s=>[...s].every(c=>p-(p=c.charCodeAt()%2),p=2)
<input id=I value="Evenst-ring"><button onclick="console.log(f(I.value))">Run</button>

ETHproductions

Posted 2016-10-13T05:42:44.623

Reputation: 47 880

41 characters in Node.js: s=>[...Buffer(s)].every(c=>p-(p=c&1),p=2) – Mwr247 – 2016-10-13T20:02:50.677

6

Brain-Flak, 138 114 112 84 + 3 = 87 bytes

Thanks 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.

0 '

Posted 2016-10-13T05:42:44.623

Reputation: 3 439

Nice! I was going I'd get a bflack answer on this one. Empty input is undefined, so you can go with the shorter one. – James – 2016-10-13T14:49:49.650

You can save 10 bytes by not using the height of the stack when you compute mod 2. Just change the beginning ([]){{} -> { and remove ([]) from just before the close of the first loop. – Riley – 2016-10-13T15:37:26.717

1Thanks @Riley, I have been looking into reducing the size of the mod 2 and I think that the whole thing can be made into {({}(())){({}[()]<(()[{}])>)}{}({}<>)<>}<> (42 bytes). This was derived from your original modulus. To make it work with your program an additional +1 nilad needs to be added: {({}(())){({}[()]<(()[{}])>)}{}({}()<>)<>}<> – 0 ' – 2016-10-13T17:26:21.453

95% of my original one was from the wiki. You saved me a ton of bytes with the new mod 2. I knew there had to be a better, I just didn't have time to find it. Thanks!

– Riley – 2016-10-13T17:41:25.463

5

Pyth (fork), 9 bytes

.A%R2.+CM

No Try It Online link because the fork does not have its own version in the online interpreters.

Explanation:

       CM       Map characters to their ASCII codes.
     .+         Get deltas (differences between consecutive character codes)
  %R2           Take the modulo of each base 2
.A              all are truthy (all deltas are odd)

Steven H.

Posted 2016-10-13T05:42:44.623

Reputation: 2 841

5

Brachylog, 17 bytes

@c:{:2%}a@b:{l1}a

Try it online!

Explanation

@c                   Input to a list of char codes
  :{:2%}a            Apply X mod 2 for each X in the list of char codes
         @b          Split the list into a list of lists where each sublist elements are the
                       same, e.g. turn [1,0,1,1,0,0] into [[1],[0],[1,1],[0,0]]
           :{l1}a    The length of each sublist must be 1

Fatalize

Posted 2016-10-13T05:42:44.623

Reputation: 32 976

5

Java 8, 77 76 72 57 bytes

a->{int i=2,b=1;for(int c:a)b=i==(i=c%2)?0:b;return b>0;}

-4 bytes thanks to @Geobits.

Explanation:

Try it online.

a->{               // Method with character-array parameter and boolean return-type
  int i=2,         //  Integer `i`, starting at any integer not 0 or 1
      b=1;         //  Flag-integer `b`, starting at 1
  for(int c:a)     //  Loop over the input-array
    b=i==(i=c%2)?  //   If two adjacent characters were both odd or even:
       0           //    Set the flag-integer `b` to 0
      :            //   Else:
       b;          //    The flag-integer `b` remains the same
  return b>0;}     //  Return if the flag-integer `b` is still 1

Kevin Cruijssen

Posted 2016-10-13T05:42:44.623

Reputation: 67 575

1

The meta consensus for truthy values means you should be returning a 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;}

– Geobits – 2016-10-13T14:28:12.967

4

Brain-Flak 155 151 141 121

Includes +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...)

#compute ((mod 2) + 1) and put on other stack
{({}(())){({}[()]<(()[{}])>)}{}({}()<>)<>}<>

#compare top two (remove top 1) push on other stack (-1 for different 0 for same)
{({}[({})]<(())>){((<{}{}>))}{}({}[()]<>)<>}<>

#remove all of the top -1s
{{}}

#take the logical not of the stack height
([]<(())>){((<{}{}>))}{}

Riley

Posted 2016-10-13T05:42:44.623

Reputation: 11 345

4

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 for nil: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 prints 10 (truthy).

Annotated Program

 ,               Push the first character
       +         Push 2
    *            Replace the first character and 2 with the first character mod 2
   `             Label 3 <--------------------------------------------------------\
 ,               Push the next the character                                      |
 +               Push a duplicate of it                                           |
               + Push 10                                                          |
 *               Replace the 10 and the duplicate with their difference           |
 '               Pop and if not zero (the read char is not 10) goto label 1 >-\   |
 +               Push a duplicate of the character which must be newline (10) |   |
  '              Pop and goto label 2 >---------------------------------------+-\ |
 `               Label 1 <----------------------------------------------------/ | |
       +         Push 2                                                         | |
    *            Replace the character and 2 with the character mod 2           | |
 +               Duplicate it ^                                                 | |
   +             Roll the top three items on the stack. The top goes to         | |
                   the bottom. The top three items are now                      | |
                   (from top to bottom) the current character, the previous     | |
                   character, the current character (all modded by 2).          | |
 *               Replace the current character and previous character           | |
                   with their difference                                        | |
   '             Pop if nonzero goto label 3 >----------------------------------+-/
     +           Push zero                                                      |
  `              Label 2 <------------------------------------------------------/
.                Print out the number on top of the stack
                    0 if we came by not following the goto label 3
                   10 if we came by going to label 2

0 '

Posted 2016-10-13T05:42:44.623

Reputation: 3 439

3

Perl, 24 + 1 (-p) = 25 bytes

-4 bytes thanks to @Ton Hospel !

s/./$&&v1/eg;$_=!/(.)\1/

Needs -p flag. Outputs 1 is the string is even, nothing otherwise. For instance :

perl -pe 's/./$&&v1/eg;$_=!/(.)\1/' <<< "#define
Hello World"

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.

Dada

Posted 2016-10-13T05:42:44.623

Reputation: 8 279

1The right method but not completely golfed out. s/./$&&v1/eg;$_=!/(.)\1/. PS (ord$&)%2 could have been written as 1&ord$& – Ton Hospel – 2016-10-13T07:48:15.757

@TonHospel Damn, I was happy I found that... But I tend to forget about bitwise operations on strings.Thanks a lot ! :) – Dada – 2016-10-13T07:57:10.727

@TonHospel, I haven't tried it, but can't you save a byte by using v1 itself instead of v1? – msh210 – 2018-02-27T21:52:23.257

1@msh210 No, you can only use valid identifiers as bare words, and \x01 isn't – Ton Hospel – 2018-02-27T21:58:02.763

2

J, 15 bytes

0=1#.2=/\2|3&u:

Usage

   f =: 0=1#.2=/\2|3&u:
   f 'C ode - g ol!f'
1
   f 'Code-golf'
0

Explanation

0=1#.2=/\2|3&u:  Input: string S
           3&u:  Get ordinals of each char
         2|      Take each modulo 2
     2  \        For each pair of values
      =/           Test if they are equal, 1 if true else 0
  1#.            Treat the list of integers as base 1 digits and convert to decimal
                 This is equivalent to taking the sum
0=               Is it equal to 0, 1 if true else 0, and return

miles

Posted 2016-10-13T05:42:44.623

Reputation: 15 654

2

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.

udioica

Posted 2016-10-13T05:42:44.623

Reputation: 2 381

2

Retina, 39 bytes

Byte count assumes ISO 8859-1 encoding.

S_`
%{2`
$`
}T01`p`_p
..

Mm`.¶.|^¶$
^0

Outputs 1 for truthy and 0 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

S_`

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

%{2`
$`

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

}T01`p`_o

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

from:   !"#$%...
to:    _ !"#$...

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

Mm`.¶.|^¶$

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

^0

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 was 0.

Martin Ender

Posted 2016-10-13T05:42:44.623

Reputation: 184 808

2

Clojure, 59 bytes

#(every?(fn[p](odd?(apply + p)))(partition 2 1(map int %)))

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.

#(every?(fn[p](odd?(apply + p)))(partition 2 1 %))

See it online : https://ideone.com/USeSnk

cliffroot

Posted 2016-10-13T05:42:44.623

Reputation: 1 080

2

Haskell, 42 40 bytes

all odd.(zipWith(-)=<<tail).map fromEnum

Usage example: all odd.(zipWith(-)=<<tail).map fromEnum $ "long" -> True.

How it works:

               map fromEnum         -- turn into a list of ascii values
    (zipWith(/=)=<<tail)            -- build a list of neighbor differences
all odd                             -- check if all differences are odd

Edit: @xnor saved two bytes. Thanks!

nimi

Posted 2016-10-13T05:42:44.623

Reputation: 34 639

It's a bit shorter to take differences and check if those are odd: all odd.(zipWith(-)=<<tail).map fromEnum. – xnor – 2016-10-13T12:39:14.740

2

Julia, 55 53 Bytes

f(s)=!ismatch(r"00|11",join(map(x->Int(x)%2,[s...])))

Explained

Map chars to 0|1 and check if the resulting string contains "00" or "11", which makes the string not alternating.

nyro_0

Posted 2016-10-13T05:42:44.623

Reputation: 281

2

Python, 52 bytes

f=lambda s:s==s[0]or(ord(s[0])-ord(s[1]))%2*f(s[1:])

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] or len(s)<2.


Python 2, 52 bytes

p=r=2
for c in input():x=ord(c)%2;r*=p-x;p=x
print r

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

p=2
for c in input():x=ord(c)%2;p=x/(p!=x)

Outputs via exit code. Terminates with a ZeroDivisionError when two consecutive characters have the same parities, otherwise terminates cleanly.

xnor

Posted 2016-10-13T05:42:44.623

Reputation: 115 687

2

Mathematica, 41 40 Bytes

And@@OddQ@Differences@ToCharacterCode@#&

-1 character, thanks to Martin Ender

celtschk

Posted 2016-10-13T05:42:44.623

Reputation: 4 650

2

C, 52 bytes

int f(char*s){return s[1]?(s[0]-s[1])%2?f(s+1):0:1;}

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

AlexRacer

Posted 2016-10-13T05:42:44.623

Reputation: 979

you can shorten this quite a bit by doing f(char*s){s=s[1]?(*s-s[1])%2?f(s+1):0:1;} you don't need the int, return or [0] – Etaoin Shrdlu – 2016-10-14T02:15:27.817

by doing *++s instead of the second s[1] you can change f(s+1) to f(s). that plus my previous comment bring the total down to 39; I should also add that removing return makes it not work on ideone, but it still works with gcc on windows – Etaoin Shrdlu – 2016-10-14T02:25:03.467

with one final tweak I brought it down to 38 by removing the inner ternary. f(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 lmao – Etaoin Shrdlu – 2016-10-14T03:06:06.663

1

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

Conor O'Brien

Posted 2016-10-13T05:42:44.623

Reputation: 36 228

1

C#, 69 bytes

s=>{int i=1,e=0;for(;i<s.Length;)e+=(s[i-1]+s[i++]+1)%2;return e<1;};

Full program with test cases:

using System;

namespace EvenStrings
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,bool>f= s=>{int i=1,e=0;for(;i<s.Length;)e+=(s[i-1]+s[i++]+1)%2;return e<1;};

            Console.WriteLine(f("lno")); //false

            //true:
            Console.WriteLine(f("#define"));
            Console.WriteLine(f("EvenSt-ring$!"));
            Console.WriteLine(f("long"));
            Console.WriteLine(f("abcdABCD"));
            Console.WriteLine(f("3.141"));
            Console.WriteLine(f("~"));
            Console.WriteLine(f("0123456789"));
            Console.WriteLine(f("C ode - g ol!f"));
            Console.WriteLine(f("HatchingLobstersVexinglyPopulateJuvenileFoxglove"));

            //false:
            Console.WriteLine(f("Hello World"));
            Console.WriteLine(f("PPCG"));
            Console.WriteLine(f("3.1415"));
            Console.WriteLine(f("babbage"));
            Console.WriteLine(f("Code-golf"));
            Console.WriteLine(f("Standard loopholes apply"));
            Console.WriteLine(f("Shortest answer in bytes wins"));
            Console.WriteLine(f("Happy golfing!"));
        }
    }
}

adrianmp

Posted 2016-10-13T05:42:44.623

Reputation: 1 592

Nice answer! +1 It's funny that when I try to port your answer to Java 7 it's longer than the one I have. But when I try to port my answer to C# it's longer than what you have. ;) – Kevin Cruijssen – 2016-10-13T08:34:57.907

1@KevinCruijssen Thanks, but there was a bug, which was not caught by any test case :( I'll try to find some other method later. – adrianmp – 2016-10-13T10:33:37.870

1

Pyke, 8 bytes

m.o$2m%B

Try it here!

m.o      -    map(ord, input)
   $     -   delta(^)
    2m%  -  map(> % 2, ^) 
       B - product(^)

Blue

Posted 2016-10-13T05:42:44.623

Reputation: 26 661

1

PHP, 69 Bytes

for(;$i<strlen($s=$argv[1])-1;)$d+=1-ord($s[$i++]^$s[$i])%2;echo$d<1;

solution with Regex 81 Bytes

for(;$i<strlen($s=$argv[1]);)$t.=ord($s[$i++])%2;echo 1-preg_match("#00|11#",$t);

Jörg Hülsermann

Posted 2016-10-13T05:42:44.623

Reputation: 13 026

1

PowerShell v2+, 47 bytes

-join([char[]]$args[0]|%{$_%2})-notmatch'00|11'

(Can't quite catch PowerShell's usual competitors ...)

Takes input $args[0] as a string, casts it as a char-array, loops through it |%{...}, each iteration placing the modulo on the pipeline (with implicit [char] to [int] conversion). Those are encapsulated in parens and -joined into a string, which is fed into the left-hand of the -notmatch operator, checking against 00 or 11 (i.e., returns True iff the 0s and 1s alternate). That Boolean result is left on the pipeline and output is implicit.

Test Cases

PS C:\Tools\Scripts\golfing> '#define','EvenSt-ring$!','long','abcdABCD','3.141','~','0123456789','C ode - g ol!f','HatchingLobstersVexinglyPopulateJuvenileFoxglove'|%{"$_ --> "+(.\evenst-ring-c-ode-g-olf.ps1 $_)}
#define --> True
EvenSt-ring$! --> True
long --> True
abcdABCD --> True
3.141 --> True
~ --> True
0123456789 --> True
C ode - g ol!f --> True
HatchingLobstersVexinglyPopulateJuvenileFoxglove --> True

PS C:\Tools\Scripts\golfing> 'Hello World','PPCG','3.1415','babbage','Code-golf','Standard loopholes apply','Shortest answer in bytes wins','Happy golfing!'|%{"$_ --> "+(.\evenst-ring-c-ode-g-olf.ps1 $_)}
Hello World --> False
PPCG --> False
3.1415 --> False
babbage --> False
Code-golf --> False
Standard loopholes apply --> False
Shortest answer in bytes wins --> False
Happy golfing! --> False

AdmBorkBork

Posted 2016-10-13T05:42:44.623

Reputation: 41 581

1

><>, 29 27 bytes

i2%\0 n;n 1<
0:i/!?-}:%2^?(

Outputs 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

Aaron

Posted 2016-10-13T05:42:44.623

Reputation: 3 689

1

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!

Lee W

Posted 2016-10-13T05:42:44.623

Reputation: 521

You can save 6 bytes by replacing =~/^0?(10)*1?$/ with !~/(.)\1/ (or !~/00|11/). – Jordan – 2016-10-13T19:23:08.813

You can get it down to 30 + 1 bytes with the -n flag and input on stdin: ruby -ne 'p gsub(/./){$&.ord%2}!~/(.)\1/'. – Jordan – 2016-10-13T19:29:47.043

1

Perl 6,  47  26 bytes

{?all .ords.rotor(2=>-1).map({(.[0]+^.[1])%2})}
{[~](.ords X%2)!~~/(.)$0/}

Expanded:

# bare block lambda with implicit parameter $_
{
  [~](             # reduce using concatenation operator ( no space chars )
    .ords X[%] 2   # the ordinals cross modulus with 2 ( 1 or 0 )
  # ^-- implicit method call on $_
  )

  ![~~]            # negating meta operator combined with smartmatch operator

  / ( . ) $0 /     # is there a character followed by itself?
}

Brad Gilbert b2gills

Posted 2016-10-13T05:42:44.623

Reputation: 12 713

1

Scala, 54 bytes

(_:String)sliding 2 map(t=>t(0)%2!=t(1)%2)reduce(_&&_)

I'm sure this can be improved.

corvus_192

Posted 2016-10-13T05:42:44.623

Reputation: 1 889

1

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

Mwr247

Posted 2016-10-13T05:42:44.623

Reputation: 3 494

1

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.

CWallach

Posted 2016-10-13T05:42:44.623

Reputation: 11

Welcome to PPCG! All answers need to be full programs or callable functions whereas this appears to be merely a question body. Please include the full function in your answer or turn this into a full program.

– Martin Ender – 2016-10-13T22:09:58.870

0

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.

Nitrodon

Posted 2016-10-13T05:42:44.623

Reputation: 9 181

0

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.

Magic Octopus Urn

Posted 2016-10-13T05:42:44.623

Reputation: 19 422

0

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.

Zacharý

Posted 2016-10-13T05:42:44.623

Reputation: 5 710

0

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)

sonrad10

Posted 2016-10-13T05:42:44.623

Reputation: 535

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. – Mego – 2016-10-13T23:16:01.410

0

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

milk

Posted 2016-10-13T05:42:44.623

Reputation: 3 043

0

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.

Stewie Griffin

Posted 2016-10-13T05:42:44.623

Reputation: 43 471

0

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

rnso

Posted 2016-10-13T05:42:44.623

Reputation: 1 635

0

Clean, 55 bytes

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

user42682

Posted 2016-10-13T05:42:44.623

Reputation: