Skip to content

Instantly share code, notes, and snippets.

@ztellman
Created August 29, 2012 03:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ztellman/3506622 to your computer and use it in GitHub Desktop.
Save ztellman/3506622 to your computer and use it in GitHub Desktop.
(ns dojo.core
(:require
[clojure.string :as str]))
;;;
(def digits
[[" _ " "| |" "|_|"]
[" " " |" " |"]
[" _ " " _|" "|_ "]
[" _ " " _|" " _|"]
[" " "|_|" " |"]
[" _ " "|_ " " _|"]
[" _ " "|_ " "|_|"]
[" _ " " |" " |"]
[" _ " "|_|" "|_|"]
[" _ " "|_|" " _|"]])
(defn print-digit-string [[a b c]]
(println (str a "\n" b "\n" c)))
(defn print-digit [n]
(print-digit-string (nth digits n)))
(def digit->digit-string
(zipmap
(range 10)
(map #(nth digits %) (range 10))))
(def digit-string->digit
(zipmap
(vals digit->digit-string)
(keys digit->digit-string)))
(defn third [s]
(nth s 2))
(defn number->string [n]
(let [digits (->> n (format "%09d") (map str) (map read-string))
digit-strings (map digit->digit-string digits)]
(->> [(map first digit-strings)
(map second digit-strings)
(map third digit-strings)]
(interpose "\n")
(map #(apply str %))
(apply str))))
;;;
(defn n-partitioned-seq [partition-size seqs]
(when (every? seq seqs)
(cons
(map #(take partition-size %) seqs)
(lazy-seq
(n-partitioned-seq partition-size
(map #(drop partition-size %) seqs))))))
(defn digit-string-seq [s]
(let [s (n-partitioned-seq 3 s)]
(map
#(map (partial apply str) %)
s)))
(defn spit-file [f nums]
(->> nums
(map number->string)
(#(interleave % (repeat "\n\n")))
(apply str)
(spit f)))
(defn read-file [f]
(->> f
slurp
str/split-lines
(partition-all 4)
(map #(take 3 %))
(map digit-string-seq)
(map #(map digit-string->digit %))))
(defn digit-seq->number [s]
(->> s (apply str) read-string))
(defn digit-seqs->numbers [s]
(map digit-seq->digit s))
;;;
(defn checksum [n]
(let [digits (->> n str (map str) (map read-string))
total (->> digits
reverse
(map vector (range 1 10))
(map #(apply * %))
(apply +))]
(rem total 11)))
;;;
(defn digit-seq->string-and-state [s]
(let [num? (every? (complement nil?) s)
valid? (and num? (zero? (checksum (digit-seq->number s))))]
(cond
(and num? valid?)
(apply str s)
(and num? (not valid?))
(str (apply str s) " ERR")
:else
(str (apply str (map #(or % "?") s)) " ILL"))))
(defn digit-seqs->string-and-states [s]
(map digit-seq->string-and-state s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment