import Problems.PVersusNP.Millennium import Mathlib.Tactic.DeriveFintype /-! # A linear-time palindrome decider Copy the input into two reversed work stacks. Move the scratch copy back onto the input stack, then drain the input and the retained reversed copy in parallel. The output alphabet is Boolean, independently of the finite input alphabet. -/ namespace Millennium.Examples.Palindrome noncomputable section open Turing Computability StateTransition inductive Stack where | input | scratch | backwards | output deriving DecidableEq, Fintype inductive Phase where | copy | restore | compare deriving DecidableEq, Fintype abbrev Alphabet (α : Type) : Stack → Type | .input => α | .scratch | .backwards => Option α | .output => Bool abbrev Register (α : Type) := Option α × Bool /-- In the successful restore branch a symbol exists. Keeping the fallback inside this instruction lets the machine work for the empty alphabet too. -/ private noncomputable def putInput (α : Type) : TM2.Stmt (Alphabet α) Phase (Register α) := by classical exact if h : Nonempty α then .push .input (fun v => v.1.getD (Classical.choice h)) (.goto fun _ => .restore) else .halt noncomputable def machine (α : Type) [Fintype α] [DecidableEq α] : FinTM2 where K := Stack k₀ := .input k₁ := .output Γ := Alphabet α Λ := Phase main := .copy σ := Register α initialState := (none, true) Γk₀Fin := inferInstanceAs (Fintype α) m | .copy => .pop .input (fun v x => (x, v.2)) (.branch (fun v => v.1.isSome) (.push .scratch (fun v => v.1) (.push .backwards (fun v => v.1) (.goto fun _ => .copy))) (.goto fun _ => .restore)) | .restore => .pop .scratch (fun v x => (x.join, v.2)) (.branch (fun v => v.1.isSome) (putInput α) (.goto fun _ => .compare)) | .compare => .pop .input (fun v x => (x, v.2)) (.branch (fun v => v.1.isSome) (.pop .backwards (fun v x => (none, v.2 && decide (v.1 = x.join))) (.goto fun _ => .compare)) (.push .output (fun v => v.2) (.load (fun _ => (none, true)) .halt))) variable {α : Type} [Fintype α] [DecidableEq α] /-- Reachable configurations store only real symbols on the work stacks. -/ def cfg (l : Option Phase) (v : Register α) (inp scratch backwards : List α) (out : List Bool) : (machine α).Cfg where l := l var := v stk | .input => inp | .scratch => scratch.map some | .backwards => backwards.map some | .output => out /-- A running configuration at one of the three loop labels. -/ abbrev atPhase (phase : Phase) (v : Register α) (inp s r : List α) (out : List Bool) := cfg (some phase) v inp s r out macro "pal_step" : tactic => `(tactic| (simp [atPhase, FinTM2.step, TM2.step, TM2.stepAux, machine, cfg, putInput, *] try (congr <;> first | rfl | (funext k; cases k <;> rfl) | (simp; done)))) theorem copy_cons (v : Register α) (a : α) (inp s r : List α) (out : List Bool) : (machine α).step (atPhase .copy v (a :: inp) s r out) = some (atPhase .copy (some a, v.2) inp (a :: s) (a :: r) out) := by pal_step theorem copy_nil (v : Register α) (s r : List α) (out : List Bool) : (machine α).step (atPhase .copy v [] s r out) = some (atPhase .restore (none, v.2) [] s r out) := by pal_step theorem restore_cons (v : Register α) (a : α) (inp s r : List α) (out : List Bool) : (machine α).step (atPhase .restore v inp (a :: s) r out) = some (atPhase .restore (some a, v.2) (a :: inp) s r out) := by have hex : Nonempty α := ⟨a⟩ pal_step theorem restore_nil (v : Register α) (inp r : List α) (out : List Bool) : (machine α).step (atPhase .restore v inp [] r out) = some (atPhase .compare (none, v.2) inp [] r out) := by pal_step theorem compare_cons (v : Register α) (a b : α) (xs ys : List α) (out : List Bool) : (machine α).step (atPhase .compare v (a :: xs) [] (b :: ys) out) = some (atPhase .compare (none, v.2 && decide (a = b)) xs [] ys out) := by pal_step theorem compare_nil (v : Register α) (out : List Bool) : (machine α).step (atPhase .compare v [] [] [] out) = some (cfg none (none, true) ([] : List α) [] [] (v.2 :: out)) := by pal_step /-- A single transition as a timed run. -/ private def oneStep {s t : (machine α).Cfg} (h : (machine α).step s = some t) : EvalsToInTime (machine α).step s (some t) 1 := { steps := 1 evals_in_steps := by simpa [flip, Option.bind] using h steps_le_m := le_rfl } private def follow {s t u : (machine α).Cfg} {m n : ℕ} (a : EvalsToInTime (machine α).step s (some t) m) (b : EvalsToInTime (machine α).step t (some u) n) : EvalsToInTime (machine α).step s (some u) (m + n) := (Nat.add_comm n m) ▸ EvalsToInTime.trans _ m n _ _ _ a b /-- After consuming the input, each work stack has acquired its reverse. -/ def copyRun (inp : List α) (v : Register α) (s r : List α) (out : List Bool) : EvalsToInTime (machine α).step (atPhase .copy v inp s r out) (some (atPhase .restore (none, v.2) [] (inp.reverse ++ s) (inp.reverse ++ r) out)) (inp.length + 1) := by induction inp generalizing v s r with | nil => simpa using oneStep (copy_nil v s r out) | cons a xs ih => have h := follow (oneStep (copy_cons v a xs s r out)) (ih (some a, v.2) (a :: s) (a :: r)) simpa [List.reverse_cons, List.append_assoc, Nat.add_comm 1] using h /-- Drain the scratch stack back onto the input, preserving the reversed copy. -/ def restoreRun (s : List α) (v : Register α) (inp r : List α) (out : List Bool) : EvalsToInTime (machine α).step (atPhase .restore v inp s r out) (some (atPhase .compare (none, v.2) (s.reverse ++ inp) [] r out)) (s.length + 1) := by induction s generalizing v inp with | nil => simpa using oneStep (restore_nil v inp r out) | cons a xs ih => have h := follow (oneStep (restore_cons v a inp xs r out)) (ih (some a, v.2) (a :: inp)) simpa [List.reverse_cons, List.append_assoc, Nat.add_comm 1] using h /-- Drain equally long stacks together. An earlier mismatch remains recorded. -/ def compareRun (xs ys : List α) (same : xs.length = ys.length) (v : Register α) (out : List Bool) : EvalsToInTime (machine α).step (atPhase .compare v xs [] ys out) (some (cfg none (none, true) ([] : List α) [] [] ((v.2 && decide (xs = ys)) :: out))) (xs.length + 1) := by induction xs generalizing ys v with | nil => cases ys with | nil => simpa using oneStep (compare_nil v out) | cons b ys => simp at same | cons a xs ih => cases ys with | nil => simp at same | cons b ys => have agree : ((v.2 && decide (a = b)) && decide (xs = ys)) = (v.2 && decide (a :: xs = b :: ys)) := by by_cases hab : a = b <;> simp [hab] have h := follow (oneStep (compare_cons v a b xs ys out)) (ih ys (by simpa using same) (none, v.2 && decide (a = b))) simpa only [agree, List.length_cons, Nat.add_comm 1] using h theorem init_eq (inp : List α) : initList (machine α) inp = atPhase .copy (none, true) inp [] [] [] := by unfold atPhase initList cfg congr funext k cases k <;> rfl theorem halt_eq (out : List Bool) : haltList (machine α) out = cfg none (none, true) ([] : List α) [] [] out := by unfold haltList cfg congr funext k cases k <;> rfl /-- Each phase takes at most one step per symbol and one final transition. -/ def run (inp : List α) : EvalsToInTime (machine α).step (initList (machine α) inp) (some (haltList (machine α) [decide (inp = inp.reverse)])) (3 * inp.length + 3) := by have hc := copyRun inp (none, true) [] [] [] have hr := restoreRun inp.reverse (none, true) [] inp.reverse [] have he := compareRun inp inp.reverse (by simp) (none, true) [] simp only [List.append_nil, List.reverse_reverse, List.length_reverse, Bool.true_and] at hc hr he rw [init_eq, halt_eq] have h := follow (follow hc hr) he rw [show 3 * inp.length + 3 = (inp.length + 1) + (inp.length + 1) + (inp.length + 1) by omega] by_cases equal : inp = inp.reverse <;> simpa [equal] using h /-- The polynomial-time witness for comparison with the reversed input. -/ noncomputable def decider (α : Type) [Fintype α] [DecidableEq α] : TM2ComputableInPolyTime (fin_encoding_string α).encode finEncodingBoolBool.encode (fun inp => decide (inp = inp.reverse)) where tm := machine α inputAlphabet := Equiv.refl _ outputAlphabet := Equiv.refl _ time := 3 * Polynomial.X + 3 outputsFun inp := by show EvalsToInTime (machine α).step (initList (machine α) (List.map id inp)) (some (haltList (machine α) (List.map id [decide (inp = inp.reverse)]))) ((3 * Polynomial.X + 3 : Polynomial ℕ).eval inp.length) simpa using run inp /-- Over every finite alphabet, the language of words equal to their reversal is in P. -/ theorem palindromes_in_P (α : Type) [Fintype α] : InPolynomialTime (fin_encoding_string α) (fun inp => inp = inp.reverse) := by classical exact ⟨_, decider α, fun _ => by simp⟩ #print axioms palindromes_in_P end end Millennium.Examples.Palindrome