Thej Kiran
Thej Kiran

Reputation: 31

Regular expression for strings containing a's in multiples of 3

Can someone please tell me how to generate a regular expression for strings in which number of a's is a multiple of 3? The alphabet set is {a,b}.

I tried to construct a DFA for it first and then derive a RE from that. What I got was ((ba*)(ba*)(ba*))*.

Upvotes: 3

Views: 3634

Answers (3)

d3ll_in_algovacay
d3ll_in_algovacay

Reputation: 1

For those asking the inverse DFA, i.e., accepts the language šæ={š‘¤āˆˆ{š‘Ž,š‘}āˆ— āˆ£ prevents the number of 'š‘Ž's to be a multiple of 3}

the answer would be
bāˆ—+(bāˆ—abāˆ—abāˆ—ab*)āˆ—a+(bāˆ—abāˆ—abāˆ—ab*)āˆ—aa

This regular expression matches strings over the alphabet {a, b} where:

  • b* represents zero or more occurrences of 'b'.
  • (b*ab*ab*ab*)*a represents zero or more occurrences of the pattern 'b', followed by one 'a', followed by zero or more 'b's, repeated three times, followed by one 'a'.
  • (b*ab*ab*ab*)*aa represents zero or more occurrences of the pattern 'b', followed by one 'a', followed by zero or more 'b's, repeated three times, followed by two 'a's

, covering all possible combinations of non-multiple-of-3 'a's (3n+1,3n+2).

Upvotes: 0

TOM SEBASTIAN
TOM SEBASTIAN

Reputation: 1

My answer would be ((b*)a(b*)a(b*)a(b*))*

Upvotes: -1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522311

I would write the pattern as:

^b*(?:(?:ab*){3})*$

This matches:

  • ^ from the start of the string
  • b* optional leading b zero or more times
  • (?:
    • (?:ab*){3} match a followed by zero or more b 3 times
  • )* match this group zero or more times
  • $ end of the string

Demo

Upvotes: 3

Related Questions