public static Automaton Intersection(Automaton a1, Automaton a2) { if (a1.IsSingleton) { return(a2.Run(a1.Singleton) ? a1.CloneIfRequired() : BasicAutomata.MakeEmpty()); } if (a2.IsSingleton) { return(a1.Run(a2.Singleton) ? a2.CloneIfRequired() : BasicAutomata.MakeEmpty()); } if (a1 == a2) { return(a1.CloneIfRequired()); } var transitions1 = Automaton.GetSortedTransitions(a1.GetStates()); var transitions2 = Automaton.GetSortedTransitions(a2.GetStates()); var c = new Automaton(); var worklist = new LinkedList <StatePair>(); var newstates = new Dictionary <StatePair, StatePair>(); var p = new StatePair(c.Initial, a1.Initial, a2.Initial); _ = worklist.AddLast(p); newstates.Add(p, p); while (worklist.Count > 0) { p = worklist.RemoveAndReturnFirst(); p.S.Accept = p.FirstState.Accept && p.SecondState.Accept; var t1 = transitions1[p.FirstState.Number]; var t2 = transitions2[p.SecondState.Number]; for (int n1 = 0, b2 = 0; n1 < t1.Length; n1++) { while (b2 < t2.Length && t2[b2].Max < t1[n1].Min) { b2++; } for (var n2 = b2; n2 < t2.Length && t1[n1].Max >= t2[n2].Min; n2++) { if (t2[n2].Max >= t1[n1].Min) { var q = new StatePair(t1[n1].To, t2[n2].To); _ = newstates.TryGetValue(q, out var r); if (r == null) { q.S = new State(); _ = worklist.AddLast(q); newstates.Add(q, q); r = q; } var min = t1[n1].Min > t2[n2].Min ? t1[n1].Min : t2[n2].Min; var max = t1[n1].Max < t2[n2].Max ? t1[n1].Max : t2[n2].Max; p.S.Transitions.Add(new Transition(min, max, r.S)); } } } } c.IsDeterministic = a1.IsDeterministic && a2.IsDeterministic; c.RemoveDeadTransitions(); c.CheckMinimizeAlways(); return(c); }