So, it’s finals time and I came across this problem in an old exam:
Give a regular expression that denotes diff(x) where:
- diff(x) is the number of 1's in x minus the number of 0's in x
- 1 <= diff(x) <= 3
e.g.
diff(10110100111) = 7-4 = 3
diff(11100011) = 5-3 = 2
diff(10011) = 3-2 = 1
it should not be possible to build a regex as desired. if it was you’d have a finite state automaton necessarily implementing an unbounded counter in order to distinguish between inputs
0^n1^n111and0^n1^n1111. obviously this cannot be achieved, at least in terms of theory (it can be achieved, however, if the difference between the number of 1s and 0s in any prefix ofxis bounded by a constant).that might be irrelevant in practice as virtually every common regex engine is more powerful than a regex recognizer but it might be relevant in the context of an exam question.