tags:

views:

217

answers:

4

What is a regular expression for strings of 0 and 1 with an even number of zeros and an even number of ones?

I have something like (1*01*01*)*(0*10*10*)*.

Does it look good?

+3  A: 

1100 is in the language, but doesn't match your expression. 10101 is not in the language, but your expression matches it.

I'd suggest starting by drawing a DFA. There's a pretty obvious 4-state machine that recognizes this language. (Is it possible to do better?) The empty string is in the language, so the start state is an accepting state. Are there other accepting states? For a non-accepting state S, is there a prefix that takes you from start->S? Is there a way to loop from S back to S without hitting an accepting state? Is there suffix that takes you from S back to an accepting state?

Jim Lewis
+1  A: 

A counterexample for your given regular expression is 01010101.

You may find that writing a regular expression for this particular problem is not going to be possible (unless you use some non-regular extensions to the usual regular expression language).

As mentioned by Jim Lewis below, this should indeed be a solvable problem.

Greg Hewgill
The set of all strings over {0,1} with an even number of 0's and an even number of 1's is most certainly regular. A DFA with four states should suffice.
Jim Lewis
@Jim Lewis: Thanks, on further consideration you're quite right.
Greg Hewgill
@Greg, I've often wondered why people strike out stuff that they later discover they disagree with. I tend to just delete it and rephrase the answer. It appears to me that the strikeout adds no value to the final answer, and our "education" can be seen in the history if anyone's interested anyway. Just curious since I've seen quite a few people do it.
paxdiablo
@Pax: If the edit is in response to a comment, doing it as a strikethrough leaves enough context for the comment to still make sense.
Jim Lewis
@paxdiablo: Perhaps I was thinking that an edited answer would cause Jim's comment to no longer make sense, and I wanted to provide the context for that. Also, it reminds future readers that even those with high rep who have been around for a while are not infallible. :)
Greg Hewgill
+5  A: 

Well, this is probably homework, but what the heck:

^(00|11|(01|10)(00|11)*(01|10))*$

Edit: simplified!

tloflin
+1: Nice work. For anybody wants to try this out interactively, try http://www.gskinner.com/RegExr/
brainjam
@tloflin: Did you use JFLAP? I did and it gave exactly the same answer :)
tiftik
@tiftik, haha no, I used Notepad. But I did start with a DFSM and reduced it, so I'm not surprised.
tloflin
That's clever..
Ipsquiggle
A: 

@tmp = $str =~ /0/g;

print scalar @tmp % 2 == 0 ? 'even' : 'odd';

jing
This is not a regular expression. This is a program.
tiftik