Regular expression for languages with limit on repeated letters

286 Views Asked by At

I'm working through some mathematical Regex questions and I was wondering if you could review some of my answers.

(1) L={w ∈ {0,1}* | w contains at least three repeated 1s}

(0|1)*111(0|1)*

(2) L = {w ∈ {0,1,2}* | w cannot have 4 repeatd 2s}

I'm still trying to figure this one out and would appreciate any help!

Also the regular expression format is in mathematical format. So not the coding format

1

There are 1 best solutions below

0
On BEST ANSWER

Your first expression is fine.

For the second you can think of words as being broken up by blocks of one, two, or three $2$s. Before the first such block, if any, we can have any string of $0$s and $1$s, including the empty string, so let’s start the regular expression with $(0\mid 1)^*$. A block of $2$s must have the form $2\mid 22\mid 222$, and it must either end the word or be followed by a $0$ or a $1$ and optionally by any further string of $0$s and $1$s before the next $2$. We’ll take care of the latter type first: each of them takes the form $(2\mid 22\mid 222)(0\mid 1)(0\mid 1)^*$, and there can be any number of them, so at this point we have

$$(0\mid 1)^*\big((2\mid 22\mid 222)(0\mid 1)(0\mid 1)^*\big)^*\;.\tag{1}$$

Finally, an acceptable word can end with $0$ or $1$, in which case $(1)$ already covers it, or it can end in a block of up to three $2$s. Thus, a regular expression that does the job is

$$(0\mid 1)^*\big((2\mid 22\mid 222)(0\mid 1)(0\mid 1)^*\big)^*(\varepsilon\mid 2\mid 22\mid222)\;.$$