Aurast
Aurast

Reputation: 87

Need a Context-Free grammar with 5 times as many of one character as the other

I'm pretty sure I've actually got one, but it has 42 construction rules and doesn't generalize well. How can I do it with fewer construction rules?

The language is {a,b}* where the number of a's is five times the number of b's.

I know that for a language {a^n (concatenate) b^m; m = 5n} it would just be

S = aSbbbbb | λ

But when the characters can be in any order, I'm lost.

Upvotes: 2

Views: 1495

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122476

First of all, observe that if a sentence has 5 times as many characters as the other, it'll always look something like aaabaabaaaaa. So one sentence can be aaaaab or aaabaa. Another observation is that whenever we add a b, we must add five a characters.

The following grammar indeed has five times as many a characters as b characters:

S = AS | λ
A = Baaaaa | aBaaaa | aaBaaa | aaaBaa | aaaaBa | aaaaaB
B = bS | Sb

We start with S which can either by empty (which satisfies the requirement) or A.

The rule for A produces at least 5 a characters and a B. Now for B, we can either place b and stop there (by choosing the empty string for S) or by starting again (by choosing A for S). This guarantees that we're always placing 5 times as many a characters as b characters.

Lastly, this grammar can easily be generalized to a grammar than needs to contain n times as many characters of one as the other (by straightforwardly extending rule A).

Upvotes: 4

Related Questions