Skip to content

Instantly share code, notes, and snippets.

@aphyr
Last active January 7, 2022 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aphyr/ab84c9a7999c8381ce540c876e0aa0db to your computer and use it in GitHub Desktop.
Save aphyr/ab84c9a7999c8381ce540c876e0aa0db to your computer and use it in GitHub Desktop.
wordle.core=> (-> words (without* "TARENIFYOH")
(antifixed* [[4 \S] [3 \L]])
(fixed* [[0 \S] [2 \U]]))
#{"SLUMP" "SLUBB"}
(ns wordle.core
(:require [clojure [pprint :refer [pprint]]
[set :as set]]
[clojure.java.io :as io]
[dom-top.core :refer [loopr]]
))
(def words
(with-open [r (io/reader (io/resource "words.txt"))]
(->> (line-seq r)
(filter (partial re-find #"^[a-zA-Z]{5}$"))
(into #{}))))
(defn conj-set
"Conj, but constructs sets from nil."
[xs x]
(if xs
(conj xs x)
#{x}))
(def index
"A vector of positions to maps of characters to sets of words."
(loopr [index (vec (repeat 5 {}))]
[word words]
(recur
(loopr [i 0
index index]
[c (seq word)]
(recur (inc i)
(update-in index [i c] conj-set word))
index))))
(defn fixed
"Takes a set of possible words and constrains them to those which have the
given [index char] address."
[words addr]
(-> (get-in index addr)
(set/intersection words)))
(defn anti-addrs
"Takes an address and returns complementary addresses: those with c at *not*
i."
[[i c]]
(->> (range 5)
(remove #{i})
(mapv (fn [i] [i c]))))
(defn antifixed
"Takes a set of possible words and constrains them to those which contain the
given character, but NOT at the [index char] address."
[words addr]
(let [candidates (->> (anti-addrs addr)
(map (partial get-in index))
(reduce set/union))]
(-> candidates
(set/difference (fixed words addr))
(set/intersection words))))
(defn without
"Takes a set of possible words and removes those which do not contain the
given character at any position."
[words c]
(->> index
(map #(get % c))
(reduce set/difference words)))
(defn without*
"Takes a set of words and removes every character in the given collection."
[words chars]
(reduce without words chars))
(defn fixed*
"Takes a set of words and a collection of addrs, and fixes those addresses in
the word set."
[words addrs]
(reduce fixed words addrs))
(defn antifixed*
"Takes a set of words and a collection of addrs, and antifixes those
addresses in the word set."
[words addrs]
(reduce antifixed words addrs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment