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