Implemented failure function algorithm with a simple interface

This commit is contained in:
martin 2023-09-10 19:46:41 +02:00
parent 1ae2757573
commit ecd9f50029
3 changed files with 91 additions and 0 deletions

View File

@ -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 = () => (
<Routes>
<Route path={ "/" } element={ <HomePage /> } />
<Route path={ "/simplify-truths" } element={ <TruthTablePage /> } />
<Route path={ "/failure-function" } element={ <FailureFunctionPage /> } />
<Route path={ "*" } element={ <PageNotFound /> } />
</Routes>
);

View File

@ -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<ReadonlyArray<FFProps>>()
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 (
<Layout title={ "Failure function" }>
<div class={ "container mx-auto max-w-2xl overflow-auto" }>
<p>Failure Function</p>
<form onsubmit={ onSubmit }>
<Input ref={ inputRef } inputClass={ "rounded-2xl w-full h-10 px-3" } />
</form>
<table class={ "mb-3" }>
<thead>
<tr>
<For each={ result() }>
{ ({ char }) =>
<th class={ "border border-black" }>{ char }</th>
}
</For>
</tr>
</thead>
<tbody>
<tr>
<For each={ result() }>
{ ({ index }) =>
<td class={ "border border-black" }>{ index }</td>
}
</For>
</tr>
</tbody>
</table>
</div>
</Layout>
);
}
export default FailureFunctionPage;

View File

@ -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
}