From ecd9f500299f067ce401f31e7a14ea5cae1aaf39 Mon Sep 17 00:00:00 2001 From: martin Date: Sun, 10 Sep 2023 19:46:41 +0200 Subject: [PATCH] Implemented failure function algorithm with a simple interface --- src/app.tsx | 2 ++ src/pages/failureFunction.tsx | 66 +++++++++++++++++++++++++++++++++++ src/utils/failureFunction.ts | 23 ++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 src/pages/failureFunction.tsx create mode 100644 src/utils/failureFunction.ts diff --git a/src/app.tsx b/src/app.tsx index 1ec60f6..3fb1d92 100644 --- a/src/app.tsx +++ b/src/app.tsx @@ -4,11 +4,13 @@ import TruthTablePage from "./pages/truth-table"; import PageNotFound from "./pages/404"; import { render } from "solid-js/web"; import { type Component } from "solid-js"; +import FailureFunctionPage from "./pages/failureFunction"; const App: Component = () => ( } /> } /> + } /> } /> ); diff --git a/src/pages/failureFunction.tsx b/src/pages/failureFunction.tsx new file mode 100644 index 0000000..6129755 --- /dev/null +++ b/src/pages/failureFunction.tsx @@ -0,0 +1,66 @@ +/* @refresh reload */ + +import { Component, createSignal } from "solid-js"; +import { Input } from "../components/input"; +import Layout from "../components/layout"; +import { failureFunction } from "../utils/failureFunction"; +import { For } from "solid-js/web"; + +type FFProps = { char: string, index: number } + +const FailureFunctionPage: Component = () => { + let inputRef: HTMLInputElement | undefined = undefined; + + const [result, setResult] = createSignal>() + + function onSubmit(e: Event) { + e.preventDefault() + if (inputRef) { + const input = inputRef.value; + const splitInput = input.split("") + const output = failureFunction(input) + + if (output.length !== splitInput.length) { + console.error("Something went wrong") + } + else { + setResult(output.map((value, index) => { + return { char: splitInput[index], index: value } as FFProps + })) + } + } + } + + return ( + +
+

Failure Function

+
+ +
+ + + + + { ({ char }) => + + } + + + + + + + { ({ index }) => + + } + + + +
{ char }
{ index }
+
+
+ ); +} + +export default FailureFunctionPage; diff --git a/src/utils/failureFunction.ts b/src/utils/failureFunction.ts new file mode 100644 index 0000000..e39b48c --- /dev/null +++ b/src/utils/failureFunction.ts @@ -0,0 +1,23 @@ +export function failureFunction(P: String, m = P.length): number[] { + // No proper prefix for string of length 1: + const arr = [0] + let i = 0, j = 1 + + while (j < m) { + if (P[i] == P[j]) { + i++ + arr.push(i) + j++; + } + // The first character didn't match: + else if (i == 0) { + arr.push(0) + j++ + } + // Mismatch after at least one matching character: + else { + i = arr[i - 1] + } + } + return arr +}