Skip to content

Instantly share code, notes, and snippets.

@sw1nn
Created July 14, 2022 17:57
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 sw1nn/3356c77498249b8496a44a7910cb1d71 to your computer and use it in GitHub Desktop.
Save sw1nn/3356c77498249b8496a44a7910cb1d71 to your computer and use it in GitHub Desktop.
(ns regroup
(:require [clojure.string :as str]
[clojure.test.check :as tc]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
))
(defn regroup [s n]
(let [patt (re-pattern (str "(?x:\n"
"^.{0," n "}$| # single short? group is whole pattern\n"
"^.{" n "}(?!..{" n ",})| # group match not followed by another full group\n"
"^.{1," n "}?| # short? group match reluctant\n"
"(?<!^).{" n "}+ # full group match possessive not at the start\n"
")"))]
(->> (str/replace s "-" "")
(re-seq patt)
(str/join "-"))))
(comment
(def char-license-plate
"Generates license plate characters."
(gen/fmap char
(gen/frequency [[70(gen/choose 65 90)]
[29 (gen/choose 48 57)]
[1 (gen/choose 45 45)]])))
(def license-plate (gen/such-that
#(not (re-find #"(^-|-$|--)" %))
(gen/fmap str/join
(gen/vector char-license-plate 3 18))))
(def property
(prop/for-all [s license-plate
n (gen/choose 1 10)]
(let [v (regroup s n)
patt (re-pattern (str "^(?:.{1,"n"}|(?:.{1,"n"}-)?(?:.{"n"}-)*.{"n"})$"))]
(re-matches patt v))))
(tc/quick-check 100000 property)
(regroup "A5-GG-B88" 3) ;=> "A-5GG-B88"
(regroup "A5-GG-B88" 2) ;=> "A-5G-GB-88"
(regroup "6776" 2) ;=> "67-76"
(regroup "F33" 1) ;=> "F-3-3"
(regroup "IIO" 7) ;=> "IIO"
(regroup "A5G-GB" 3) ;=> "A5-GGB"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment