import Problems.PVersusNP.Millennium import Problems.PVersusNP.Machines.WordStacks /-! # A linear-time palindrome decider Copy the input into two reversed work stacks. Restore one copy and compare it with the other. Each loop uses the timed programs in `Machines.WordStacks`. -/ namespace Millennium.Examples.Palindrome noncomputable section open Turing Computability StateTransition open Millennium.Machines.WordStacks -- Keep the example's original names available to its callers. export Millennium.Machines.WordStacks (Stack Phase Alphabet Register machine cfg atPhase copy_cons copy_nil restore_cons restore_nil compare_cons compare_nil copyRun restoreRun compareRun init_eq halt_eq) variable {α : Type} [Fintype α] [DecidableEq α] /-- 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] convert h using 1 congr 5 /-- 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