计算机科学 · 第 4 册 · 本科二年级

University Computer Science — Year 2

本书暂未推出简体中文版。现有版本:English。

University Computer Science — Year 2 · 本科二年级

21Finite Automata

Is a typed string a decimal number, such as -12.5e3? A program can decide with one table and one loop:

// dfa_demo.rs: is the string a decimal number such as -12.5e3? One table and one loop.
const START: usize = 0;
const ACCEPT: [bool; 8] = [false, false, true, false, true, false, false, true];
// columns: digit, sign, point, e or E; rows: the 8 states; NO: no transition
const NO: usize = usize::MAX;
const TABLE: [[usize; 4]; 8] = [
    [2, 1, NO, NO],  // 0 start
    [2, NO, NO, NO], // 1 after the sign
    [2, NO, 3, 5],   // 2 in the integer part (accepting)
    [4, NO, NO, NO], // 3 after the point
    [4, NO, NO, 5],  // 4 in the fraction (accepting)
    [7, 6, NO, NO],  // 5 after the e
    [7, NO, NO, NO], // 6 after the exponent's sign
    [7, NO, NO, NO], // 7 in the exponent (accepting)
];

pub fn class(c: char) -> Option<usize> {
    match c {
        '0'..='9' => Some(0),
        '+' | '-' => Some(1),
        '.' => Some(2),
        'e' | 'E' => Some(3),
        _ => None,
    }
}

pub fn is_number(s: &str) -> (bool, Vec<usize>) {
    let (mut q, mut path) = (START, vec![START]);
    for c in s.chars() {
        match class(c).map(|k| TABLE[q][k]) {
            Some(next) if next != NO => q = next,
            _ => return (false, path), // no transition: rejected at once
        }
        path.push(q);
    }
    (ACCEPT[q], path)
}
Listing 21.1. A decimal number recogniser: eight states, four classes of characters code/bachelor-2/21-finite-automata/listings/dfa_demo.rs
$ rustc --edition 2021 -O -o dfa_demo dfa_demo.rs && ./dfa_demo
"-12.5e3"  number   states 0 1 2 2 3 4 5 7
"+0.25E-7" number   states 0 1 2 3 4 4 5 6 7
"42"       number   states 0 2 2
"3."       no       states 0 2 3
".5"       no       states 0
"1e"       no       states 0 2 5
"12a"      no       states 0 2 2
"--1"      no       states 0 1
""         no       states 0
Output 21.1. Nine strings and the states they visit.

The program remembers nothing about the string but one number from 0 to 7, its state, and it reads each character once. Such a device is a finite automaton. This chapter defines automata exactly, gives them a power they seem to lack, guessing, shows that guessing adds nothing but costs states, sometimes exponentially many, and builds automata for combinations of conditions. The next chapter connects them with the patterns of regular expressions, and finds what no finite automaton can do.

You already know

The Year 1 volume: a finite-state machine has a finite set of states, a start state, and a transition function from a state and an input to the next state; it may also produce outputs. Proofs by induction on the length of a word, or by structural induction. Sets, maps, and the set of subsets of a set, which has 2n2^n elements when the set has nn.

21.1 Words and languages

Definition 21.1 (Alphabet, word)

An alphabet is a finite nonempty set Σ\Sigma, whose elements are letters. A word over Σ\Sigma is a finite sequence of letters w=a1a2⋯anw = a_1 a_2 \cdots a_n; its length is ∣w∣=n|w| = n. The empty word ε\varepsilon has length 0. The set of all words is Σ∗\Sigma^*, and there are ∣Σ∣n|\Sigma|^n words of length nn.

The concatenation of uu and vv is the word uvuv, uu followed by vv: it is associative, ε\varepsilon is neutral, and ∣uv∣=∣u∣+∣v∣|uv| = |u| + |v|. In the hook, Σ\Sigma is the set of characters, and the program reads "-12.5e3" as a word of length 7.

Definition 21.2 (Language)

A language over Σ\Sigma is a set of words, finite or infinite. For languages LL and MM, the concatenation is LM={uv:u∈L, v∈M}LM = \{uv : u \in L,\ v \in M\}; the powers are L0={ε}L^0 = \{\varepsilon\} and Ln+1=LnLL^{n+1} = L^n L; and the star of LL is L∗=⋃n≥0LnL^* = \bigcup_{n \ge 0} L^n, the words made by concatenating any number of words of LL, none included.

For example, {a,b}∗\{a, b\}^* is every word over {a,b}\{a, b\}, {ab}∗={ε,ab,abab,… }\{ab\}^* = \{\varepsilon, ab, abab, \dots\}, and {a}{b}∗\{a\}\{b\}^*, written ab∗ab^*, is the words made of one aa and then any number of bb’s.

Definition 21.3 (Prefix, suffix, factor, subword)

Let w=uxvw = uxv with u,x,vu, x, v words. Then uu is a prefix of ww, vv a suffix, and xx a factor: a block of consecutive letters. A subword of ww is a word obtained by deleting letters of ww, not necessarily consecutive.

The word abcaabca has the prefixes ε,a,ab,abc,abca\varepsilon, a, ab, abc, abca; bcbc is a factor; aaaa is a subword but not a factor. A word of length nn has n+1n + 1 prefixes and n+1n + 1 suffixes.

21.2 Deterministic automata

Definition 21.4 (Deterministic finite automaton)

A deterministic finite automaton (DFA) is A=(Q,Σ,δ,q0,F)A = (Q, \Sigma, \delta, q_0, F): a finite set of states QQ, an alphabet Σ\Sigma, a transition function δ\delta, a partial map from Q×ΣQ \times \Sigma to QQ, a start state q0q_0, and a set F⊆QF \subseteq Q of accepting states. The extended transition function δ∗\delta^* on words is defined by δ∗(q,ε)=q\delta^*(q, \varepsilon) = q and δ∗(q,wa)=δ(δ∗(q,w),a)\delta^*(q, wa) = \delta(\delta^*(q, w), a), undefined as soon as one step is. AA accepts ww when δ∗(q0,w)\delta^*(q_0, w) is defined and lies in FF, and the language recognised by AA is L(A)L(A), the set of words it accepts.

The automaton of the hook. A missing arrow is a missing transition: the string is rejected there. The accepting states have a double circle.
The automaton of the hook. A missing arrow is a missing transition: the string is rejected there. The accepting states have a double circle.

Proposition 21.5 (Reading in two parts)

For every state qq and words u,vu, v: δ∗(q,uv)=δ∗(δ∗(q,u),v)\delta^*(q, uv) = \delta^*(\delta^*(q, u), v), both sides being defined or undefined together.

Proof. By induction on ∣v∣|v|. For v=εv = \varepsilon both sides are δ∗(q,u)\delta^*(q, u). If v=wav = wa, then δ∗(q,uwa)=δ(δ∗(q,uw),a)=δ(δ∗(δ∗(q,u),w),a)=δ∗(δ∗(q,u),wa)\delta^*(q, uwa) = \delta(\delta^*(q, uw), a) = \delta(\delta^*(\delta^*(q, u), w), a) = \delta^*(\delta^*(q, u), wa), by the definition, the hypothesis for ww, and the definition again; each equality holds also when one side is undefined. ∎

This is what makes an automaton a streaming program: after reading uu, the state δ∗(q0,u)\delta^*(q_0, u) is all that is needed to continue, whatever uu was. The run_from method of automaton.rs, the library of this chapter’s listings, is δ∗\delta^* written as a fold over the letters.

Definition 21.6 (Complete automaton)

A DFA is complete if δ(q,a)\delta(q, a) is defined for every state qq and letter aa. Any DFA is made complete, with the same language, by adding a non-accepting sink state ss and sending every missing transition, and every letter from ss, to ss.

Definition 21.7 (Accessible, co-accessible, trim)

A state qq is accessible if q=δ∗(q0,u)q = \delta^*(q_0, u) for some word uu, and co-accessible if δ∗(q,v)∈F\delta^*(q, v) \in F for some word vv. An automaton is trim if all its states are both.

Proposition 21.8 (Trimming)

Removing from a DFA every state that is not both accessible and co-accessible, with the transitions that touch it, leaves the recognised language unchanged. Both sets are computed by a graph search, in time linear in the number of transitions.

Proof. If ww is accepted, every state on its run is accessible (by a prefix of ww) and co-accessible (by the rest of ww), so the run survives the removal. Conversely, removing states and transitions can only remove runs, so no new word is accepted. Accessible states are those reachable from q0q_0 in the graph of the transitions; co-accessible states are those from which FF is reachable, that is, those reachable from FF in the reversed graph. ∎

Definition 21.9 (Recognisable language)

A language is recognisable if some finite automaton recognises it.

21.3 Nondeterministic automata

Consider the words over {a,b}\{a, b\} whose third letter from the end is aa. Reading from the left, a program cannot know which letter will be third from the end. It would be easy if it could guess: on each aa, guess “this is the one”, then check that exactly two letters follow.

Definition 21.10 (Nondeterministic finite automaton)

A nondeterministic finite automaton (NFA) is A=(Q,Σ,Δ,I,F)A = (Q, \Sigma, \Delta, I, F) where Δ⊆Q×Σ×Q\Delta \subseteq Q \times \Sigma \times Q is a set of transitions, so that a state may have several transitions, or none, on the same letter, and I⊆QI \subseteq Q is a set of start states. A run on w=a1⋯anw = a_1 \cdots a_n is a sequence q0q1⋯qnq_0 q_1 \cdots q_n with q0∈Iq_0 \in I and (qi−1,ai,qi)∈Δ(q_{i-1}, a_i, q_i) \in \Delta; AA accepts ww if some run on ww ends in FF.

Left: an NFA for “the third letter from the end is a”; state 0 has two transitions on a. Right: an NFA for a*b*c* with spontaneous transitions (dashed).
Left: an NFA for “the third letter from the end is aa”; state 0 has two transitions on aa. Right: an NFA for a∗b∗c∗a^*b^*c^* with spontaneous transitions (dashed).

A nondeterministic automaton is not a program that guesses well; it is a definition by existence of a run. It is also convenient to allow moves that read nothing.

Definition 21.11 (Spontaneous transition, closure)

An NFA with spontaneous transitions also has a set of pairs (p,q)(p, q), written p→εqp \xrightarrow{\varepsilon} q, which a run may take without reading a letter. The ε\varepsilon-closure of a set SS of states is the set of states reachable from SS by spontaneous transitions alone, SS included: the states reachable from SS in the graph of those transitions.

    /// The states reachable from the set by spontaneous transitions: a graph search.
    pub fn closure(&self, set: &Subset) -> Subset {
        let mut out = set.clone();
        let mut todo: Vec<usize> = set.iter().copied().collect();
        while let Some(q) = todo.pop() {
            for &r in &self.eps[q] {
                if out.insert(r) {
                    todo.push(r); // new: its own spontaneous moves follow
                }
            }
        }
        out
    }

    /// One letter from a closed set of states, then the closure.
    pub fn step(&self, set: &Subset, a: usize) -> Subset {
        let next = set.iter().flat_map(|&q| self.delta[q][a].iter().copied()).collect();
        self.closure(&next)
    }
Listing 21.2. The closure by a graph search, and one letter followed by the closure code/bachelor-2/21-finite-automata/listings/automaton.rs

Proposition 21.12 (Removing spontaneous transitions)

Let cl(q)\mathrm{cl}(q) be the closure of {q}\{q\}. The NFA with the same states and start states, the transitions (q,a,r)(q, a, r) for every rr in the closure of {r′:(p,a,r′)∈Δ, p∈cl(q)}\{r' : (p, a, r') \in \Delta,\ p \in \mathrm{cl}(q)\}, no spontaneous transition, and the accepting states {q:cl(q)∩F≠∅}\{q : \mathrm{cl}(q) \cap F \ne \emptyset\}, recognises the same language.

Proof. A run of the original automaton on a1⋯ana_1 \cdots a_n is a sequence of spontaneous moves, a letter, spontaneous moves, and so on. Cut it just before each letter: from state qi−1q_{i-1} at the cut, it moves spontaneously within cl(qi−1)\mathrm{cl}(q_{i-1}), reads aia_i, then moves spontaneously to the next cut qiq_i, which is exactly a new transition (qi−1,ai,qi)(q_{i-1}, a_i, q_i); after the last letter it moves spontaneously to FF, which makes qnq_n accepting in the new automaton. Conversely, each new transition and each new accepting state unfolds into such moves of the original one. ∎

$ rustc --edition 2021 -O -o epsilon epsilon.rs && ./epsilon
closure of 0: {0, 1, 2}
closure of 1: {1, 2}
closure of 2: {2}
state 0: a -> [0, 1, 2], b -> [1, 2], c -> [2]  accepting
state 1: a -> [], b -> [1, 2], c -> [2]  accepting
state 2: a -> [], b -> [], c -> [2]  accepting
1093 of 1093 words up to length 6 judged alike; 84 accepted
Output 21.2. The closures of a∗b∗c∗a^*b^*c^*’s states, the automaton without spontaneous transitions, and a check on every word up to length 6.

21.4 The subset construction

An NFA can be run by a program that keeps the set of states it might be in. That set takes finitely many values, which makes it the state of a DFA.

Method 21.13 (The subset construction)

Given an NFA (Q,Σ,Δ,I,F)(Q, \Sigma, \Delta, I, F), build a DFA whose states are sets of NFA states. The start state is cl(I)\mathrm{cl}(I). From a set SS and a letter aa, the transition goes to cl({r:(p,a,r)∈Δ, p∈S})\mathrm{cl}(\{r : (p, a, r) \in \Delta,\ p \in S\}). A set is accepting if it contains a state of FF. Build only the sets reachable from the start, with a queue.

    /// The subset construction, from the start set, keeping accessible subsets only.
    pub fn determinise(&self) -> (Dfa, Vec<Subset>) {
        let first = self.closure(&self.start.iter().copied().collect());
        let mut index = HashMap::from([(first.clone(), 0)]);
        let (mut subsets, mut delta) = (vec![first], Vec::new());
        let mut todo = VecDeque::from([0]);
        while let Some(i) = todo.pop_front() {
            let mut row = Vec::new();
            for a in 0..self.alphabet.len() {
                let target = self.step(&subsets[i], a);
                let j = *index.entry(target.clone()).or_insert_with(|| {
                    subsets.push(target);
                    todo.push_back(subsets.len() - 1);
                    subsets.len() - 1
                });
                row.push(Some(j));
            }
            delta.push(row);
        }
        let accept = subsets.iter().map(|s| s.iter().any(|&q| self.accept[q])).collect();
        (Dfa { alphabet: self.alphabet.clone(), delta, start: 0, accept }, subsets)
    }
Listing 21.3. The subset construction: each new set gets a number and joins the queue code/bachelor-2/21-finite-automata/listings/automaton.rs

Theorem 21.14 (The subset construction is correct)

For every word ww, the state of the DFA after reading ww is the set of NFA states at which some run on ww can end. Hence the DFA recognises the language of the NFA, and a language is recognisable by an NFA if and only if it is recognisable by a DFA.

Proof. By induction on ∣w∣|w|. For w=εw = \varepsilon, the runs on ε\varepsilon are the spontaneous moves from II, which end exactly in cl(I)\mathrm{cl}(I), the start state. Suppose the claim holds for ww, with set SS. A run on wawa is a run on ww, ending in some p∈Sp \in S, then a transition (p,a,r)(p, a, r), then spontaneous moves: it ends exactly in the closure of the rr’s, which is the transition of the DFA from SS on aa. So the DFA’s state after ww contains a state of FF if and only if some run on ww ends in FF. Conversely a DFA is an NFA with one start state and at most one transition per state and letter. ∎

$ rustc --edition 2021 -O -o subset subset.rs && ./subset
DFA state  subset of NFA states   on a       on b
        0  {0}                   {0,1}      {0}
        1  {0,1}                 {0,1,2}    {0,2}
        2  {0,1,2}               {0,1,2,3}  {0,2,3}
        3  {0,2}                 {0,1,3}    {0,3}
        4  {0,1,2,3}             {0,1,2,3}  {0,2,3}    accepting
        5  {0,2,3}               {0,1,3}    {0,3}      accepting
        6  {0,1,3}               {0,1,2}    {0,2}      accepting
        7  {0,3}                 {0,1}      {0}        accepting
abb    NFA true   DFA true
bab    NFA false  DFA false
baab   NFA true   DFA true
abba   NFA false  DFA false
Output 21.3. The determinisation of “the third letter from the end is aa”: eight sets of states.

The DFA remembers which of the last three letters were aa: the set {0,2,3}\{0, 2, 3\} means the last letter was bb and the two before it were aa. That needs 232^3 states, and no DFA can do with fewer.

Theorem 21.15 (The blow-up is unavoidable)

Let LkL_k be the words over {a,b}\{a, b\} whose kk-th letter from the end is aa. An NFA with k+1k + 1 states recognises LkL_k, and every DFA that recognises LkL_k has at least 2k2^k states; the subset construction produces exactly 2k2^k.

Proof. Let u≠vu \ne v be two words of length kk, and ii the first position, counting from 0, where they differ; say uu has aa there and vv has bb. Append bib^i: in ubiub^i and vbivb^i, that position is now kk-th from the end, so ubi∈Lkub^i \in L_k and vbi∉Lkvb^i \notin L_k. In a DFA recognising LkL_k, if δ∗(q0,u)=δ∗(q0,v)\delta^*(q_0, u) = \delta^*(q_0, v) then by Proposition 21.5 δ∗(q0,ubi)=δ∗(q0,vbi)\delta^*(q_0, ub^i) = \delta^*(q_0, vb^i), and the two words would be both accepted or both rejected. So the 2k2^k words of length kk lead to 2k2^k different states. The NFA of the figure has k+1k + 1 states; the reachable sets of the subset construction are {0}∪T\{0\} \cup T for the 2k2^k sets T⊆{1,…,k}T \subseteq \{1, \dots, k\} of positions among the last kk letters that hold an aa, all reached. ∎

$ rustc --edition 2021 -O -o blowup blowup.rs && ./blowup
 k  NFA states  DFA states   2^k  reached by the 2^k words  pairs told apart
 1           2           2     2                         2                 1
 2           3           4     4                         4                 6
 3           4           8     8                         8                28
 4           5          16    16                        16               120
 5           6          32    32                        32               496
 6           7          64    64                        64              2016
 7           8         128   128                       128              8128
 8           9         256   256                       256             32640
 9          10         512   512                       512            130816
10          11        1024  1024                      1024            523776
11          12        2048  2048                      2048           2096128
12          13        4096  4096                      4096           8386560
Output 21.4. For k=1k = 1 to 12, the states of both automata, and the proof’s argument checked on every pair of words of length kk.

A set of words that must lead to pairwise different states, as here, is a fooling set; it gives a lower bound on the size of every DFA for the language (Exercise 21.10).

History

Finite automata come from the 1950s. Stephen Kleene’s paper of 1956, in the collection Automata Studies, started from models of nerve nets and characterised the “events” a finite automaton can recognise; that result is the next chapter’s main theorem. In 1959 Michael Rabin and Dana Scott defined nondeterministic automata and proved that the subset construction removes the nondeterminism, the theorem of this section.

21.5 Combining automata

Definition 21.16 (Product automaton)

The product of two complete DFAs (P,Σ,δ,p0,F)(P, \Sigma, \delta, p_0, F) and (Q,Σ,γ,q0,G)(Q, \Sigma, \gamma, q_0, G) has the states P×QP \times Q, the start (p0,q0)(p_0, q_0) and the transitions (p,q)→a(δ(p,a),γ(q,a))(p, q) \xrightarrow{a} (\delta(p, a), \gamma(q, a)): it runs both automata at once.

Proposition 21.17 (Closure under the Boolean operations)

If LL and MM are recognisable, so are Σ∗∖L\Sigma^* \setminus L, L∪ML \cup M and L∩ML \cap M.

Proof. Take complete DFAs for LL and MM. Swapping accepting and other states of the first gives the complement: the run on every word is defined and ends in exactly one state, accepting in one automaton if and only if not in the other. By induction on ∣w∣|w|, the product’s state after ww is the pair of the two states after ww; so with accepting states F×GF \times G it recognises L∩ML \cap M, and with (F×Q)∪(P×G)(F \times Q) \cup (P \times G) it recognises L∪ML \cup M. ∎

Completeness matters for the complement: an incomplete automaton rejects some words by having no run at all, and swapping its accepting states leaves them rejected (Exercise 21.2). The product of “even length” and “starts with aa” has six states, and not all of them are useful:

$ rustc --edition 2021 -O -o product product.rs && ./product
pair    on a    on b    accepting  accessible  co-accessible
(0,0)   (1,1)   (1,2)   false      true        true
(0,1)   (1,1)   (1,1)   true       true        true
(0,2)   (1,2)   (1,2)   false      true        false
(1,0)   (0,1)   (0,2)   false      false       true
(1,1)   (0,1)   (0,1)   false      true        true
(1,2)   (0,2)   (0,2)   false      true        false
trim automaton: 3 of 6 states
accepted words of length 0..8: [0, 0, 2, 0, 8, 0, 32, 0, 128]
Output 21.5. The product for the intersection, its useless states, and the number of accepted words of each length.
The product of “even length” (first component) and “starts with a” (0: start, 1: began with a, 2: began with b). Grey: (1, 0) is not accessible; (1, 2) and (0, 2) cannot reach the accepting state. The trim automaton keeps three states.
The product of “even length” (first component) and “starts with aa” (0: start, 1: began with aa, 2: began with bb). Grey: (1,0)(1, 0) is not accessible; (1,2)(1, 2) and (0,2)(0, 2) cannot reach the accepting state. The trim automaton keeps three states.

The counts, 2n−12^{n-1} words of every even length n≥2n \ge 2, are computed from the automaton by dynamic programming: the number of words leading to each state, letter after letter (Exercise 21.4).

21.6 Automata as programs

A DFA runs in constant time per letter: one table lookup, as in the hook. An NFA can be run either by building the DFA first, or by simulating it on the fly, keeping the set of possible states, which costs up to the number of NFA states per letter but builds nothing. With at most 64 states, the set fits in the bits of one machine word, and a step is a few shifts and ORs (Exercise 21.11). On LkL_k, over two million letters:

$ rustc --edition 2021 -O -o simulate_vs_determinise simulate_vs_determinise.rs && ./simulate_vs_determinise
  k   NFA, sets    NFA, bits   DFA states   build (ms)          DFA
     ns/letter    ns/letter                             ns/letter
  4          100          5.3           16          0.0          3.9
 10          137          7.6         1024          0.7          7.8
 16          207          8.9        65536         79.8         82.5
Output 21.6. Simulating LkL_k’s NFA with sets as ordered trees or as bits, or building its DFA and running it, on the laptop.

The DFA wins while it is small. At k=16k = 16 it has 65 536 states, takes 80 ms to build, and runs slower than the simulation by bits, since its table no longer fits in the processor’s caches and each letter costs a memory access (Chapter 12). Programs that search text with patterns face the same choice, and many build the DFA lazily, one state the first time it is needed.

21.7 Exercises

Exercise 21.1 ★

Give the run of the automaton of Listing 21.1 on 0.0, -.5, 1E+10, 7e3.5 and +, and say which are accepted.

Solution

Solution of Exercise 21.1.

$ rustc --edition 2021 -O -o exo_runs exo_runs.rs && ./exo_runs
"0.0"    number states [0, 2, 3, 4]
"-.5"    no     states [0, 1]
"1E+10"  number states [0, 2, 5, 6, 7, 7]
"7e3.5"  no     states [0, 2, 5, 7]
"+"      no     states [0, 1]
Output 21.7. The five runs.

0.0 and 1E+10 are accepted. -.5 stops in state 1: after a sign, only a digit may come. 7e3.5 stops in state 7: the exponent has no point. + ends in state 1, which is not accepting.

Exercise 21.2 ★

The DFA with states 0 and 1, start 0, accepting 1, and the transitions 0→a10 \xrightarrow{a} 1 and 1→b11 \xrightarrow{b} 1 recognises ab∗ab^*. Swap its accepting and other states: which language do you get? Which words are missing from the complement, and how is it repaired?

Solution

Solution of Exercise 21.2.

$ rustc --edition 2021 -O -o exo_complement exo_complement.rs && ./exo_complement
word   a b*    swapped  complement
""     false   true     true
"a"    true    false    false
"b"    false   false    true
"ab"   true    false    false
"ba"   false   false    true
"abb"  true    false    false
"aab"  false   false    true
Output 21.8. The automaton, its swapped version and the true complement.

The swapped automaton accepts only ε\varepsilon: every other word either ends in state 1, now rejecting, or has no run. The words without a run in ab∗ab^*’s automaton, such as bb, baba or aabaab, are rejected by both, though the complement must accept them. Completing first with a sink state, then swapping, gives the complement (Proposition 21.17).

Exercise 21.3 ★

Build a DFA with three states that recognises the binary writings of the multiples of 3 (the empty word standing for 0), and prove it correct.

Solution

Solution of Exercise 21.3.

$ rustc --edition 2021 -O -o exo_mult3 exo_mult3.rs && ./exo_mult3
state 0: 0 -> 0, 1 -> 1  (start, accepting)
state 1: 0 -> 2, 1 -> 0
state 2: 0 -> 1, 1 -> 2
agrees with x % 3 == 0 for x = 0 .. 999: true
Output 21.9. The three states, and a check.

The state is the value read so far, modulo 3: reading a bit cc after a prefix of value xx gives the value 2x+c2x + c, so state rr goes to (2r+c) mod 3(2r + c) \bmod 3. By induction on the length, δ∗(0,w)=val(w) mod 3\delta^*(0, w) = \mathrm{val}(w) \bmod 3: true for ε\varepsilon, of value 0, and kept by each step since (2x+c) mod 3=(2(x mod 3)+c) mod 3(2x + c) \bmod 3 = (2(x \bmod 3) + c) \bmod 3. So ww is accepted, ending in state 0, exactly when its value is a multiple of 3.

Exercise 21.4 ★

Build a complete DFA for the words over {a,b}\{a, b\} that do not contain the factor bbbb, and find a recurrence for the number cnc_n of such words of length nn.

Solution

Solution of Exercise 21.4.

$ rustc --edition 2021 -O -o exo_count exo_count.rs && ./exo_count
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]
Output 21.10. c0c_0 to c15c_{15}, computed from the automaton.

States: 0, the last letter is not bb (or no letter yet); 1, the last letter is bb; 2, bbbb has been seen, a sink. States 0 and 1 accept. Let xnx_n and yny_n count the words of length nn ending in states 0 and 1. Then xn+1=xn+ynx_{n+1} = x_n + y_n (an aa from either) and yn+1=xny_{n+1} = x_n (a bb from state 0 only), so cn=xn+ync_n = x_n + y_n satisfies cn+1=xn+1+yn+1=cn+xn=cn+cn−1c_{n+1} = x_{n+1} + y_{n+1} = c_n + x_n = c_n + c_{n-1}, with c0=1c_0 = 1 and c1=2c_1 = 2: the Fibonacci numbers.

Exercise 21.5 ★★

Apply the subset construction to the NFA with states 0, 1, 2, start 0, accepting 2, and the transitions 0→a,b00 \xrightarrow{a, b} 0, 0→a10 \xrightarrow{a} 1 and 1→b21 \xrightarrow{b} 2. Which language is it?

Solution

Solution of Exercise 21.5.

$ rustc --edition 2021 -O -o exo_subset exo_subset.rs && ./exo_subset
0: {0}  a -> 1, b -> 0
1: {0, 1}  a -> 1, b -> 2
2: {0, 2}  a -> 1, b -> 0, accepting
Output 21.11. The three reachable sets.

From {0}\{0\}, aa leads to {0,1}\{0, 1\} and bb back to {0}\{0\}; from {0,1}\{0, 1\}, aa stays and bb leads to {0,2}\{0, 2\}, accepting; from {0,2}\{0, 2\}, aa leads to {0,1}\{0, 1\} and bb to {0}\{0\}. Only 3 of the 8 subsets are reachable. The language is the words that end with abab.

Exercise 21.6 ★★

A program computes the closure of a set by adding, once, the targets of the spontaneous transitions of its states. On the automaton of a∗b∗c∗a^*b^*c^*, which words does it get wrong, and why?

Solution

Solution of Exercise 21.6.

$ rustc --edition 2021 -O -o exo_closure_bug exo_closure_bug.rs && ./exo_closure_bug
""     one step: false  closure: true
"a"    one step: false  closure: true
"ab"   one step: true   closure: true
"abc"  one step: true   closure: true
"c"    one step: false  closure: true
Output 21.12. One spontaneous step against the closure.

From {0}\{0\}, one step adds 1 but not 2, which is two spontaneous steps away. So ε\varepsilon, aa and cc are wrongly rejected: each needs a run that passes from 0 to 2 without reading anything. Words that read a bb pass through state 1, from which one step reaches 2, and come out right. The closure is reachability in a graph, and must loop until no new state appears, as Listing 21.2 does.

Exercise 21.7 ★★

Build a DFA with four states for the words over {a,b}\{a, b\} that contain the factor abaaba, and explain what each state remembers.

Solution

Solution of Exercise 21.7.

// factor_aba.rs: a DFA for the words over {a, b} that contain the factor aba (exercise 7).
// State i: the longest suffix of what was read that is a prefix of aba has length i;
// state 3: aba has been seen.
pub const DELTA: [[usize; 2]; 4] = [
    [1, 0], // "":  a starts the pattern, b does not
    [1, 2], // "a": a again keeps "a", b makes "ab"
    [3, 0], // "ab": a completes aba, b leaves nothing
    [3, 3], // found: stay
];

pub fn contains_aba(word: &str) -> bool {
    let mut q = 0;
    for c in word.chars() {
        q = DELTA[q][if c == 'a' { 0 } else { 1 }];
    }
    q == 3
}
Searching for abaaba code/bachelor-2/21-finite-automata/exercises/factor_aba.rs

State i≤2i \le 2 means that the longest suffix of what has been read that is a prefix of abaaba has length ii; state 3 means abaaba has appeared. From state 2 (abab), a bb gives abbabb, whose suffixes bbbb, bb, ε\varepsilon are not prefixes of abaaba except ε\varepsilon: back to 0. From state 1 (aa), an aa gives aaaa, whose longest such suffix is aa: state 1. The test compares it with contains("aba") on every word up to length 10. The same idea, for any pattern, is the automaton of the text-search algorithms of Chapter 25.

Exercise 21.8 ★★

The reverse of w=a1⋯anw = a_1 \cdots a_n is an⋯a1a_n \cdots a_1. Show that if LL is recognisable, the set of the reverses of its words is recognisable.

Solution

Solution of Exercise 21.8.

Take a DFA for LL and reverse every transition: (p,a,q)(p, a, q) becomes (q,a,p)(q, a, p). Make the accepting states the start states, and the old start state the only accepting state. This is an NFA; a run of it on an⋯a1a_n \cdots a_1 from some qn∈Fq_n \in F to q0q_0 is exactly a run of the DFA on a1⋯ana_1 \cdots a_n read backwards. So the NFA recognises the reverses of the words of LL, and by Theorem 21.14 so does a DFA.

Exercise 21.9 ★★

For integers n≥1n \ge 1 and b≥2b \ge 2, build a DFA with nn states that recognises the writings in base bb of the multiples of nn, and test it.

Solution

Solution of Exercise 21.9.

// multiples.rs: the multiples of n written in base b, as a DFA on the digits (exercise 9).
// The state is the value read so far, modulo n: reading digit d sends r to (b r + d) mod n.

pub fn delta(n: u32, b: u32) -> Vec<Vec<u32>> {
    (0..n).map(|r| (0..b).map(|d| (b * r + d) % n).collect()).collect()
}

/// digits: most significant first; the empty word stands for 0.
pub fn is_multiple(n: u32, b: u32, digits: &[u32]) -> bool {
    let table = delta(n, b);
    digits.iter().fold(0, |r, &d| table[r as usize][d as usize]) == 0
}
The multiples of nn in base bb code/bachelor-2/21-finite-automata/exercises/multiples.rs

As in Exercise 21.3: reading a digit dd after a value xx gives bx+dbx + d, so the state x mod nx \bmod n goes to (b (x mod n)+d) mod n(b\,(x \bmod n) + d) \bmod n; the start and the only accepting state are 0. The test checks five pairs (n,b)(n, b), n=1n = 1 included, on every number below 2000.

Exercise 21.10 ★★★

A fooling set for LL is a set SS of words such that for any two u≠vu \ne v in SS there is a word zz with exactly one of uzuz and vzvz in LL. Show that every complete DFA recognising LL (one whose transition function is defined everywhere) has at least ∣S∣|S| accessible states, and a partial one at least ∣S∣−1|S| - 1. Find a fooling set of size 3 for the language of Exercise 21.3.

Solution

Solution of Exercise 21.10.

Let u≠vu \ne v in SS, and suppose a DFA AA for LL has δ∗(q0,u)=δ∗(q0,v)\delta^*(q_0, u) = \delta^*(q_0, v), both defined. For the word zz that tells them apart, Proposition 21.5 gives δ∗(q0,uz)=δ∗(q0,vz)\delta^*(q_0, uz) = \delta^*(q_0, vz), so uzuz and vzvz are both accepted or both rejected: a contradiction. If one of the two runs is undefined, uu or vv has no extension in LL, and at most one word of SS can be like that (two such words could not be told apart). So the words of SS lead to ∣S∣|S| different states, or ∣S∣−1|S| - 1 states and one undefined run; the completed automaton has at least ∣S∣|S| states, and the bound holds for every complete DFA. For the multiples of 3, S={ε,1,10}S = \{\varepsilon, 1, 10\}, of values 0, 1 and 2: appending ε\varepsilon separates ε\varepsilon from the others, and appending 11 separates 11 (value 3, a multiple) from 1010 (value 5).

Exercise 21.11 ★★★

Write an NFA simulation that keeps the set of states as the bits of a 64-bit word, and compare its speed with the determinised automaton for LkL_k.

Solution

Solution of Exercise 21.11.

/// Simulation with the set of states as the bits of one machine word.
fn simulate_bits(n: &Nfa, word: &[usize]) -> bool {
    let mut masks = vec![[0u64; 2]; n.delta.len()]; // successors of q on a and on b
    for (q, row) in n.delta.iter().enumerate() {
        for a in 0..2 {
            masks[q][a] = row[a].iter().fold(0, |m, &r| m | 1 << r);
        }
    }
    let mut set = 1u64 << n.start[0];
    for &a in word {
        let mut next = 0;
        let mut rest = set;
        while rest != 0 {
            let q = rest.trailing_zeros() as usize; // one state of the set
            next |= masks[q][a];
            rest &= rest - 1;
        }
        set = next;
    }
    (0..n.delta.len()).any(|q| set >> q & 1 == 1 && n.accept[q])
}
Simulation with the set of states as bits code/bachelor-2/21-finite-automata/listings/simulate_vs_determinise.rs

For each state and letter, the set of successors is precomputed as a mask. A step ORs the masks of the states in the current set, found by trailing_zeros and cleared one by one. Output 21.6 gives about 5 to 9 ns per letter, against 100 to 210 with ordered sets, and against a DFA that wins for small kk but whose 65 536 states at k=16k = 16 make each lookup a cache miss.

Exercise 21.12 ★★★

Show that if LL is recognisable, the set of the prefixes of its words is recognisable.

Solution

Solution of Exercise 21.12.

Take a trim DFA for LL (Proposition 21.8), and make every state accepting. If uu is a prefix of a word uv∈Luv \in L, the run on uvuv exists, so the run on uu exists and ends in a state of the trim automaton: accepted. Conversely, if the run on uu ends in a state qq, then qq is co-accessible, so some vv leads from qq to an accepting state, and uv∈Luv \in L. If LL is empty, the trim automaton has no state, and the language of prefixes is empty too.

21.8 Problem: Decoding the lighthouse’s light signals

Problem 21.1

Weekend problem — Decoding the lighthouse’s light signals

The lighthouse sends messages as flashes, short (ss) or long (ll). A message is a word over {s,l}\{s, l\}; the harbour reads it as it comes.

Part I — Signals as words.

  1. How many messages of length 10 are there, and how many of length at most 10?
  2. List the prefixes, suffixes and factors of length 2 of sllslsllsl.
  3. Is ssss a subword of slslslsl? A factor?
  4. Describe {s,l}∗l{s,l}∗\{s, l\}^* l \{s, l\}^* and {ss,l}∗\{ss, l\}^* in words.
  5. Show that L∗L∗=L∗L^* L^* = L^* for every language LL.
  6. Is {s}∗{l}∗={s,l}∗\{s\}^* \{l\}^* = \{s, l\}^*? Give a word that tells.

Part II — Valid messages.

A message is valid if it has an even number of long flashes and never three short flashes in a row.

  1. Build a complete DFA PP with two states for “an even number of ll”.
  2. Build a complete DFA NN with four states for “no factor ssssss”.
  3. How many states has their product, and which are accepting?
  4. Which states of the product are not co-accessible? How many states does the trim automaton keep?
  5. Run it on slslssslslss and lssslsllssslsl.
  6. Write the recurrence that counts valid messages, state by state, and compute the counts for lengths 0 to 6.

Part III — A pattern near the end.

The harbour must react when the fourth flash from the end is long.

  1. Draw an NFA with 5 states for it.
  2. What does its subset construction remember after each flash?
  3. How many states does the DFA have, and what is its start state?
  4. Give two messages of length 4 that lead to different DFA states, and a suffix that tells them apart.
  5. Is the NFA’s on-the-fly simulation cheaper than the DFA here? Use Output 21.6.
  6. Why can the harbour not use an automaton that reads the message backwards?

Part IV — The blow-up.

  1. For “the kk-th flash from the end is long”, how many states do the NFA and the DFA need?
  2. Which 2k2^k words form a fooling set, and why does that prove the bound?
  3. Could a different NFA with fewer than k+1k + 1 states recognise the language?
  4. To check also that the message is valid, the harbour runs the product of the DFA of question 19 with the trim automaton of question 10. At most how many states does it have for k=4k = 4?
  5. How does Output 21.4 check the proof for k≤12k \le 12?
  6. State the result: the 2k2^k law, exactly 2k2^k states, none removable.
Solution

Solution of Problem 21.1.

1. 210=10242^{10} = 1024; 211−1=20472^{11} - 1 = 2047 of length at most 10.

2. Prefix slsl, suffix slsl; factors of length 2: slsl, llll, lsls.

3. ssss is a subword (delete both ll’s) but not a factor.

4. The messages that contain at least one long flash; the messages in which short flashes come in pairs (every maximal block of ss has even length).

5. L∗⊆L∗L∗L^* \subseteq L^* L^* since ε∈L∗\varepsilon \in L^*; and a concatenation of ii words of LL followed by jj words of LL is a concatenation of i+ji + j of them.

6. No: lsls is in {s,l}∗\{s, l\}^* but not in s∗l∗s^* l^*.

7. States EE (even, start, accepting) and OO; ll swaps them, ss keeps them.

8. States 0, 1, 2 (the number of trailing ss, all accepting) and a sink 3: ss moves ii to i+1i + 1 (2 to 3), ll moves 0, 1, 2 to 0.

9. 8 states; accepting: (E,0)(E, 0), (E,1)(E, 1), (E,2)(E, 2).

10. (E,3)(E, 3) and (O,3)(O, 3), the sink pairs, cannot reach acceptance; all states are accessible (from the start, ssssss and lssslsss reach the two sink pairs). The trim automaton keeps 6 states.

11. slslssslslss: (E,0)→(E,1)→(O,0)→(O,1)→(E,0)→(E,1)→(E,2)(E,0) \to (E,1) \to (O,0) \to (O,1) \to (E,0) \to (E,1) \to (E,2), accepted. lssslsllssslsl: after lssslsss the run is in (O,3)(O, 3), rejected.

12. Writing ei(n)e_i(n) and oi(n)o_i(n) for the words of length nn ending in (E,i)(E, i) and (O,i)(O, i): e0(n+1)=o0(n)+o1(n)+o2(n)e_0(n+1) = o_0(n) + o_1(n) + o_2(n) and o0(n+1)=e0(n)+e1(n)+e2(n)o_0(n+1) = e_0(n) + e_1(n) + e_2(n) (an ll switches the parity), and ei+1(n+1)=ei(n)e_{i+1}(n+1) = e_i(n), oi+1(n+1)=oi(n)o_{i+1}(n+1) = o_i(n) for i=0,1i = 0, 1. The valid messages of lengths 0 to 6 are 1, 1, 2, 3, 7, 12, 22.

13. States 0 to 4: 0 loops on ss and ll, 0→l10 \xrightarrow{l} 1, then i→s,li+1i \xrightarrow{s, l} i + 1 up to 4, accepting.

14. Which of the last four flashes were long: the set {0}∪T\{0\} \cup T, where TT holds the positions, among the last four, of the long ones.

15. 24=162^4 = 16 states; the start state is {0}\{0\}.

16. lssslsss and ssssssss: the suffix ε\varepsilon tells them apart, since the first has a long flash fourth from the end.

17. For k=4k = 4, the DFA has 16 states and its table fits in the caches: in Output 21.6 it runs at about 4 ns a flash, a little faster than the simulation by bits. The simulation wins only for large kk.

18. The flashes arrive one at a time and the harbour must react as they come; a backward automaton would need the whole message first. (Read backwards, the condition concerns the fourth flash from the start, which a 5-state DFA checks.)

19. k+1k + 1 for the NFA, 2k2^k for the DFA (Theorem 21.15).

20. The 2k2^k messages of length kk: any two differ first at some position ii, and the suffix sis^i puts that flash kk-th from the end, so one message becomes accepted and the other not; by Exercise 21.10, every DFA has at least 2k2^k states.

21. No. Take the pairs xi=lix_i = l^i, yi=lk−iy_i = l^{k-i} for i=0,…,ki = 0, \dots, k: xiyi=lkx_i y_i = l^k is accepted, so an accepting run passes, after xix_i, through some state qiq_i. If qi=qjq_i = q_j with i<ji < j, the run on xix_i followed by the rest of the run on yjy_j accepts li+k−jl^{i + k - j}, which has fewer than kk letters and is not in the language. So the k+1k + 1 states qiq_i are distinct.

22. At most 16×6=9616 \times 6 = 96 pairs, of which only the accessible ones need to be built.

23. It counts the states reached by the 2k2^k words of length kk, and checks, for each of the pairs, that the suffix of the proof makes exactly one of the two words accepted: 8 386 560 pairs for k=12k = 12.

24. The 2k2^k law: for “the kk-th letter from the end”, an NFA has k+1k + 1 states, and every DFA has at least 2k2^k, which the subset construction reaches exactly; none of its states can be removed or merged, since the words of length kk lead to pairwise distinguishable states.

本章定义的术语

在术语表中查看全部 1050 个术语