Initial check-in

This commit is contained in:
Ray Miller 2023-10-07 17:12:47 +01:00
commit 334eb5f4d0
11 changed files with 1014 additions and 0 deletions

40
anagram/anagram.go Normal file
View file

@ -0,0 +1,40 @@
package anagram
import (
"bufio"
"io"
"sort"
"github.com/ray1729/puzzle-solver/util"
)
type DB interface {
FindAnagrams(s string) []string
}
func toKey(s string) string {
xs := util.LowerCaseAlpha(s)
sort.Slice(xs, func(i, j int) bool { return xs[i] < xs[j] })
return string(xs)
}
type HashDBImpl map[string][]string
func Load(r io.Reader) (DB, error) {
db := make(HashDBImpl)
sc := bufio.NewScanner(r)
for sc.Scan() {
s := sc.Text()
k := toKey(s)
db[k] = append(db[k], s)
}
if err := sc.Err(); err != nil {
return nil, err
}
return db, nil
}
func (d HashDBImpl) FindAnagrams(s string) []string {
return d[toKey(s)]
}

3
assets/custom.css Normal file
View file

@ -0,0 +1,3 @@
div.center {
text-align: center;
}

1
assets/htmx.min.js vendored Normal file

File diff suppressed because one or more lines are too long

685
assets/simple.css Normal file
View file

@ -0,0 +1,685 @@
/* Global variables. */
:root,
::backdrop {
/* Set sans-serif & mono fonts */
--sans-font: -apple-system, BlinkMacSystemFont, "Avenir Next", Avenir,
"Nimbus Sans L", Roboto, "Noto Sans", "Segoe UI", Arial, Helvetica,
"Helvetica Neue", sans-serif;
--mono-font: Consolas, Menlo, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
--standard-border-radius: 5px;
/* Default (light) theme */
--bg: #fff;
--accent-bg: #f5f7ff;
--text: #212121;
--text-light: #585858;
--border: #898EA4;
--accent: #0d47a1;
--code: #d81b60;
--preformatted: #444;
--marked: #ffdd33;
--disabled: #efefef;
}
/* Dark theme */
@media (prefers-color-scheme: dark) {
:root,
::backdrop {
color-scheme: dark;
--bg: #212121;
--accent-bg: #2b2b2b;
--text: #dcdcdc;
--text-light: #ababab;
--accent: #ffb300;
--code: #f06292;
--preformatted: #ccc;
--disabled: #111;
}
/* Add a bit of transparency so light media isn't so glaring in dark mode */
img,
video {
opacity: 0.8;
}
}
/* Reset box-sizing */
*, *::before, *::after {
box-sizing: border-box;
}
/* Reset default appearance */
textarea,
select,
input,
progress {
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
}
html {
/* Set the font globally */
font-family: var(--sans-font);
scroll-behavior: smooth;
}
/* Make the body a nice central block */
body {
color: var(--text);
background-color: var(--bg);
font-size: 1.15rem;
line-height: 1.5;
display: grid;
grid-template-columns: 1fr min(45rem, 90%) 1fr;
margin: 0;
}
body > * {
grid-column: 2;
}
/* Make the header bg full width, but the content inline with body */
body > header {
background-color: var(--accent-bg);
border-bottom: 1px solid var(--border);
text-align: center;
padding: 0 0.5rem 2rem 0.5rem;
grid-column: 1 / -1;
}
body > header h1 {
max-width: 1200px;
margin: 1rem auto;
}
body > header p {
max-width: 40rem;
margin: 1rem auto;
}
/* Add a little padding to ensure spacing is correct between content and header > nav */
main {
padding-top: 1.5rem;
}
body > footer {
margin-top: 4rem;
padding: 2rem 1rem 1.5rem 1rem;
color: var(--text-light);
font-size: 0.9rem;
text-align: center;
border-top: 1px solid var(--border);
}
/* Format headers */
h1 {
font-size: 3rem;
}
h2 {
font-size: 2.6rem;
margin-top: 3rem;
}
h3 {
font-size: 2rem;
margin-top: 3rem;
}
h4 {
font-size: 1.44rem;
}
h5 {
font-size: 1.15rem;
}
h6 {
font-size: 0.96rem;
}
p {
margin: 1.5rem 0;
}
/* Prevent long strings from overflowing container */
p, h1, h2, h3, h4, h5, h6 {
overflow-wrap: break-word;
}
/* Fix line height when title wraps */
h1,
h2,
h3 {
line-height: 1.1;
}
/* Reduce header size on mobile */
@media only screen and (max-width: 720px) {
h1 {
font-size: 2.5rem;
}
h2 {
font-size: 2.1rem;
}
h3 {
font-size: 1.75rem;
}
h4 {
font-size: 1.25rem;
}
}
/* Format links & buttons */
a,
a:visited {
color: var(--accent);
}
a:hover {
text-decoration: none;
}
button,
.button,
a.button, /* extra specificity to override a */
input[type="submit"],
input[type="reset"],
input[type="button"],
label[type="button"] {
border: 1px solid var(--accent);
background-color: var(--accent);
color: var(--bg);
padding: 0.5rem 0.9rem;
text-decoration: none;
line-height: normal;
}
.button[aria-disabled="true"],
input:disabled,
textarea:disabled,
select:disabled,
button[disabled] {
cursor: not-allowed;
background-color: var(--disabled);
border-color: var(--disabled);
color: var(--text-light);
}
input[type="range"] {
padding: 0;
}
/* Set the cursor to '?' on an abbreviation and style the abbreviation to show that there is more information underneath */
abbr[title] {
cursor: help;
text-decoration-line: underline;
text-decoration-style: dotted;
}
button:enabled:hover,
.button:not([aria-disabled="true"]):hover,
input[type="submit"]:enabled:hover,
input[type="reset"]:enabled:hover,
input[type="button"]:enabled:hover,
label[type="button"]:hover {
filter: brightness(1.4);
cursor: pointer;
}
.button:focus-visible,
button:focus-visible:where(:enabled),
input:enabled:focus-visible:where(
[type="submit"],
[type="reset"],
[type="button"]
) {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
/* Format navigation */
header > nav {
font-size: 1rem;
line-height: 2;
padding: 1rem 0 0 0;
}
/* Use flexbox to allow items to wrap, as needed */
header > nav ul,
header > nav ol {
align-content: space-around;
align-items: center;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
list-style-type: none;
margin: 0;
padding: 0;
}
/* List items are inline elements, make them behave more like blocks */
header > nav ul li,
header > nav ol li {
display: inline-block;
}
header > nav a,
header > nav a:visited {
margin: 0 0.5rem 1rem 0.5rem;
border: 1px solid var(--border);
border-radius: var(--standard-border-radius);
color: var(--text);
display: inline-block;
padding: 0.1rem 1rem;
text-decoration: none;
}
header > nav a:hover,
header > nav a.current,
header > nav a[aria-current="page"] {
border-color: var(--accent);
color: var(--accent);
cursor: pointer;
}
/* Reduce nav side on mobile */
@media only screen and (max-width: 720px) {
header > nav a {
border: none;
padding: 0;
text-decoration: underline;
line-height: 1;
}
}
/* Consolidate box styling */
aside, details, pre, progress {
background-color: var(--accent-bg);
border: 1px solid var(--border);
border-radius: var(--standard-border-radius);
margin-bottom: 1rem;
}
aside {
font-size: 1rem;
width: 30%;
padding: 0 15px;
margin-inline-start: 15px;
float: right;
}
*[dir="rtl"] aside {
float: left;
}
/* Make aside full-width on mobile */
@media only screen and (max-width: 720px) {
aside {
width: 100%;
float: none;
margin-inline-start: 0;
}
}
article, fieldset, dialog {
border: 1px solid var(--border);
padding: 1rem;
border-radius: var(--standard-border-radius);
margin-bottom: 1rem;
}
article h2:first-child,
section h2:first-child {
margin-top: 1rem;
}
section {
border-top: 1px solid var(--border);
border-bottom: 1px solid var(--border);
padding: 2rem 1rem;
margin: 3rem 0;
}
/* Don't double separators when chaining sections */
section + section,
section:first-child {
border-top: 0;
padding-top: 0;
}
section:last-child {
border-bottom: 0;
padding-bottom: 0;
}
details {
padding: 0.7rem 1rem;
}
summary {
cursor: pointer;
font-weight: bold;
padding: 0.7rem 1rem;
margin: -0.7rem -1rem;
word-break: break-all;
}
details[open] > summary + * {
margin-top: 0;
}
details[open] > summary {
margin-bottom: 0.5rem;
}
details[open] > :last-child {
margin-bottom: 0;
}
/* Format tables */
table {
border-collapse: collapse;
margin: 1.5rem 0;
}
td,
th {
border: 1px solid var(--border);
text-align: start;
padding: 0.5rem;
}
th {
background-color: var(--accent-bg);
font-weight: bold;
}
tr:nth-child(even) {
/* Set every other cell slightly darker. Improves readability. */
background-color: var(--accent-bg);
}
table caption {
font-weight: bold;
margin-bottom: 0.5rem;
}
/* Format forms */
textarea,
select,
input,
button,
.button {
font-size: inherit;
font-family: inherit;
padding: 0.5rem;
margin-bottom: 0.5rem;
border-radius: var(--standard-border-radius);
box-shadow: none;
max-width: 100%;
display: inline-block;
}
textarea,
select,
input {
color: var(--text);
background-color: var(--bg);
border: 1px solid var(--border);
}
label {
display: block;
}
textarea:not([cols]) {
width: 100%;
}
/* Add arrow to drop-down */
select:not([multiple]) {
background-image: linear-gradient(45deg, transparent 49%, var(--text) 51%),
linear-gradient(135deg, var(--text) 51%, transparent 49%);
background-position: calc(100% - 15px), calc(100% - 10px);
background-size: 5px 5px, 5px 5px;
background-repeat: no-repeat;
padding-inline-end: 25px;
}
*[dir="rtl"] select:not([multiple]) {
background-position: 10px, 15px;
}
/* checkbox and radio button style */
input[type="checkbox"],
input[type="radio"] {
vertical-align: middle;
position: relative;
width: min-content;
}
input[type="checkbox"] + label,
input[type="radio"] + label {
display: inline-block;
}
input[type="radio"] {
border-radius: 100%;
}
input[type="checkbox"]:checked,
input[type="radio"]:checked {
background-color: var(--accent);
}
input[type="checkbox"]:checked::after {
/* Creates a rectangle with colored right and bottom borders which is rotated to look like a check mark */
content: " ";
width: 0.18em;
height: 0.32em;
border-radius: 0;
position: absolute;
top: 0.05em;
left: 0.17em;
background-color: transparent;
border-right: solid var(--bg) 0.08em;
border-bottom: solid var(--bg) 0.08em;
font-size: 1.8em;
transform: rotate(45deg);
}
input[type="radio"]:checked::after {
/* creates a colored circle for the checked radio button */
content: " ";
width: 0.25em;
height: 0.25em;
border-radius: 100%;
position: absolute;
top: 0.125em;
background-color: var(--bg);
left: 0.125em;
font-size: 32px;
}
/* Makes input fields wider on smaller screens */
@media only screen and (max-width: 720px) {
textarea,
select,
input {
width: 100%;
}
}
/* Set a height for color input */
input[type="color"] {
height: 2.5rem;
padding: 0.2rem;
}
/* do not show border around file selector button */
input[type="file"] {
border: 0;
}
/* Misc body elements */
hr {
border: none;
height: 1px;
background: var(--border);
margin: 1rem auto;
}
mark {
padding: 2px 5px;
border-radius: var(--standard-border-radius);
background-color: var(--marked);
color: black;
}
mark a {
color: #0d47a1;
}
img,
video {
max-width: 100%;
height: auto;
border-radius: var(--standard-border-radius);
}
figure {
margin: 0;
display: block;
overflow-x: auto;
}
figcaption {
text-align: center;
font-size: 0.9rem;
color: var(--text-light);
margin-bottom: 1rem;
}
blockquote {
margin-inline-start: 2rem;
margin-inline-end: 0;
margin-block: 2rem;
padding: 0.4rem 0.8rem;
border-inline-start: 0.35rem solid var(--accent);
color: var(--text-light);
font-style: italic;
}
cite {
font-size: 0.9rem;
color: var(--text-light);
font-style: normal;
}
dt {
color: var(--text-light);
}
/* Use mono font for code elements */
code,
pre,
pre span,
kbd,
samp {
font-family: var(--mono-font);
color: var(--code);
}
kbd {
color: var(--preformatted);
border: 1px solid var(--preformatted);
border-bottom: 3px solid var(--preformatted);
border-radius: var(--standard-border-radius);
padding: 0.1rem 0.4rem;
}
pre {
padding: 1rem 1.4rem;
max-width: 100%;
overflow: auto;
color: var(--preformatted);
}
/* Fix embedded code within pre */
pre code {
color: var(--preformatted);
background: none;
margin: 0;
padding: 0;
}
/* Progress bars */
/* Declarations are repeated because you */
/* cannot combine vendor-specific selectors */
progress {
width: 100%;
}
progress:indeterminate {
background-color: var(--accent-bg);
}
progress::-webkit-progress-bar {
border-radius: var(--standard-border-radius);
background-color: var(--accent-bg);
}
progress::-webkit-progress-value {
border-radius: var(--standard-border-radius);
background-color: var(--accent);
}
progress::-moz-progress-bar {
border-radius: var(--standard-border-radius);
background-color: var(--accent);
transition-property: width;
transition-duration: 0.3s;
}
progress:indeterminate::-moz-progress-bar {
background-color: var(--accent-bg);
}
dialog {
max-width: 40rem;
margin: auto;
}
dialog::backdrop {
background-color: var(--bg);
opacity: 0.8;
}
@media only screen and (max-width: 720px) {
dialog {
max-width: 100%;
margin: auto 1em;
}
}
/* Superscript & Subscript */
/* Prevent scripts from affecting line-height. */
sup, sub {
vertical-align: baseline;
position: relative;
}
sup {
top: -0.4em;
}
sub {
top: 0.3em;
}
/* Classes for notices */
.notice {
background: var(--accent-bg);
border: 2px solid var(--border);
border-radius: 5px;
padding: 1.5rem;
margin: 2rem 0;
}

5
go.mod Normal file
View file

@ -0,0 +1,5 @@
module github.com/ray1729/puzzle-solver
go 1.21.1
require golang.org/x/text v0.13.0 // indirect

2
go.sum Normal file
View file

@ -0,0 +1,2 @@
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=

76
grep/grep.go Normal file
View file

@ -0,0 +1,76 @@
package grep
import (
"bufio"
"io"
"github.com/ray1729/puzzle-solver/util"
)
type DB interface {
FindMatches(s string) []string
}
type Node struct {
Value byte
Children []*Node
Results []string
}
func (n *Node) Add(xs []byte, s string) {
if len(xs) == 0 {
n.Results = append(n.Results, s)
return
}
x := xs[0]
var child *Node
for _, c := range n.Children {
if c.Value == x {
child = c
break
}
}
if child == nil {
child = &Node{Value: x}
n.Children = append(n.Children, child)
}
child.Add(xs[1:], s)
}
func Load(r io.Reader) (DB, error) {
db := &Node{}
sc := bufio.NewScanner(r)
for sc.Scan() {
s := sc.Text()
xs := util.LowerCaseAlpha(s)
db.Add(xs, s)
}
if err := sc.Err(); err != nil {
return nil, err
}
return db, nil
}
func (n *Node) FindMatches(s string) []string {
return n.find(util.LowerCaseAlphaOrDot(s))
}
func (n *Node) find(xs []byte) []string {
if len(xs) == 0 {
return n.Results
}
x := xs[0]
if x == '.' {
var result []string
for _, c := range n.Children {
result = append(result, c.find(xs[1:])...)
}
return result
}
for _, c := range n.Children {
if c.Value == x {
return c.find(xs[1:])
}
}
return nil
}

40
main.go Normal file
View file

@ -0,0 +1,40 @@
package main
import (
"log"
"net/http"
"os"
"github.com/ray1729/puzzle-solver/anagram"
"github.com/ray1729/puzzle-solver/grep"
"github.com/ray1729/puzzle-solver/server"
)
var grepDB grep.DB
var anagramDB anagram.DB
func init() {
f, err := os.Open("/usr/share/dict/british-english-huge")
if err != nil {
log.Fatalf("Error opening word list: %v", err)
}
defer f.Close()
grepDB, err = grep.Load(f)
if err != nil {
log.Fatalf("Error loading grep database: %v", err)
}
f.Seek(0, 0)
anagramDB, err = anagram.Load(f)
if err != nil {
log.Fatalf("Error loading anagram database: %v", err)
}
}
func main() {
s := server.New("./assets", grepDB, anagramDB)
address := ":8000"
log.Printf("Listening on %s", address)
if err := http.ListenAndServe(address, s); err != nil {
log.Fatal(err)
}
}

77
server/server.go Normal file
View file

@ -0,0 +1,77 @@
package server
import (
"fmt"
"html/template"
"log"
"net/http"
"github.com/ray1729/puzzle-solver/anagram"
"github.com/ray1729/puzzle-solver/grep"
)
func New(assetsPath string, grepDB grep.DB, anagramDB anagram.DB) http.Handler {
mux := http.NewServeMux()
mux.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(assetsPath))))
mux.HandleFunc("/", getHomePage)
mux.HandleFunc("/search", getResults(grepDB, anagramDB))
return withRequestLogger(mux)
}
func withRequestLogger(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s", r.Method, r.URL.Path, r.URL.Query())
h.ServeHTTP(w, r)
})
}
func getResults(grepDB grep.DB, anagramDB anagram.DB) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
log.Printf("error parsing form: %v", err)
http.Error(w, "error parsing form", http.StatusBadRequest)
return
}
mode := r.Form.Get("mode")
pattern := r.Form.Get("pattern")
templateParams := struct {
Preamble string
Results []string
}{}
switch mode {
case "match":
templateParams.Results = grepDB.FindMatches(pattern)
if len(templateParams.Results) > 0 {
templateParams.Preamble = fmt.Sprintf("Matches for %q:", pattern)
} else {
templateParams.Preamble = fmt.Sprintf("Found no matches for %q", pattern)
}
case "anagrams":
templateParams.Results = anagramDB.FindAnagrams(pattern)
if len(templateParams.Results) > 0 {
templateParams.Preamble = fmt.Sprintf("Anagrams of %q:", pattern)
} else {
templateParams.Preamble = fmt.Sprintf("Found no anagrams of %q", pattern)
}
case "clear":
// pass
default:
log.Printf("invalid mode: %s", mode)
http.Error(w, "invalid mode", http.StatusBadRequest)
return
}
renderTemplate(w, results, templateParams)
}
}
func getHomePage(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, home, nil)
}
func renderTemplate(w http.ResponseWriter, t *template.Template, params any) {
err := t.Execute(w, params)
if err != nil {
log.Printf("Error rendering template %s: %v", t.Name(), err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}

47
server/templates.go Normal file
View file

@ -0,0 +1,47 @@
package server
import "html/template"
var home = template.Must(template.New("home").Parse(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/assets/simple.css">
<link rel="stylesheet" href="/assets/custom.css">
<script src="/assets/htmx.min.js"></script>
<title>Anagram and Word Search</title>
</head>
<body>
<header>
<h1>Anagram and Word Search</h1>
</header>
<main>
<form action="/search" method="get" hx-boost="true" hx-target="#results" hx-replace="outerHTML" hx-on::after-request="this.reset()">
<div class="center">
<input type="text" name="pattern" required></input>
<button name="mode" value="match">Match</button>
<button name="mode" value="anagrams">Anagrams</button>
<button name="mode" value="clear">Clear</button>
</div>
</form>
<div id="results">
</div>
</main>
</body>
</html>
`))
var results = template.Must(template.New("results").Parse(`
{{ with .Preamble }}
<p>{{ . }}</p>
{{ end }}
<ul>
{{ range .Results }}
<li>{{.}}</li>
{{ end }}
</ul>
`))

38
util/util.go Normal file
View file

@ -0,0 +1,38 @@
package util
import (
"bytes"
"strings"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
func Normalize(s string) []byte {
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
s, _, _ = transform.String(t, s)
s = strings.ToLower(s)
return []byte(s)
}
func LowerCaseAlpha(s string) []byte {
result := bytes.NewBuffer(nil)
for _, x := range Normalize(s) {
if x >= 'a' && x <= 'z' {
result.WriteByte(x)
}
}
return result.Bytes()
}
func LowerCaseAlphaOrDot(s string) []byte {
result := bytes.NewBuffer(nil)
for _, x := range Normalize(s) {
if x >= 'a' && x <= 'z' || x == '.' {
result.WriteByte(x)
}
}
return result.Bytes()
}