Skip to content

Instantly share code, notes, and snippets.

@shegeley
Last active August 24, 2020 05:42
Show Gist options
  • Save shegeley/851510b9cc19daf65656e23ae75246bc to your computer and use it in GitHub Desktop.
Save shegeley/851510b9cc19daf65656e23ae75246bc to your computer and use it in GitHub Desktop.
Translating decimal number to some symbolic enumeration system consistend of distinct strings
(ns symbolic-system.utils
(:require [clojure.math.numeric-tower :as math]))
(defn symbolic-enumeration-system->decimal-number
"Translates symbolic enumeration system element that consists of distinct strings to decimal number based on number of elements in the system. System elements must be given in descending order"
[x system]
{:pre [(spec/and
(spec/valid? (spec/coll-of string?) x)
(spec/valid? (spec/coll-of string?) system)
(spec/valid? not-empty system)
(spec/valid? #(apply distinct? %) system))]
:post [#(spec/valid? int? %)]}
(loop [t x
result 0]
(if (= (count t) 0)
result
(recur
(drop 1 t)
(+ result
(* (+ 1 (.indexOf (reverse system) (first t))) (math/expt (count system) (- (count t) 1))))))))
(defn decimal-number->symbolic-enumeration-system
"Translates decimal number to some symbolic enumeration system consistend of distinct strings. System elements must be given in descending order"
[x system]
{:pre [(spec/and
(spec/valid? pos-int? x)
(spec/valid? (spec/coll-of string?) system))]}
(loop [t x
result []]
(let [c (count system)
sys (vec (reverse system))
last-symbol (get sys (mod (- t 1) c))]
(if (< t c)
(reverse
(conj result (get sys (- t 1))))
(recur
(quot (- t 1) c)
(conj result last-symbol))))))
;; Excel example
(def excel-collumn-alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
(defn collumn-number->collumn-string
"Translates collumn number (e.g 5) to string (e.g 'E') as all collumns in Excel enumerated as alphabet letters. 27 Translates to 'AA' and 28 to 'AB'. Etc."
[^Integer x]
(apply str (utils/decimal-number->symbolic-enumeration-system x (mapv str (reverse excel-collumn-alphabet)))))
(defn collumn-string->collumn-number
"Translates collumn string (e. g. 'AA') to it's number (e. g. 27) as all collumns in Excel enumerated as alphabet letters."
[^String x]
(utils/symbolic-enumeration-system->decimal-number (mapv str x) (mapv str (reverse excel-collumn-alphabet))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment