Skip to content

Instantly share code, notes, and snippets.

View egri-nagy's full-sized avatar

Attila Egri-Nagy egri-nagy

View GitHub Profile
@egri-nagy
egri-nagy / latin_square.clj
Last active November 16, 2017 01:41
Generating latin squares with core.logic in Clojure
;; adapted from the Sudoku solver in `The Joy of Clojure 2nd Edition' 2014 by Michal Fogus and Chris Houser, Chater 16 Thinking Programs
(require '[clojure.core.logic :as l] ;;the logic engine
'[clojure.core.logic.fd :as fd]) ;;dealing with finite domains (integer numbers)
(defn latin-squares [n num-of-sols] ;; n - size of the square, num-fo-sols - number of solutions
(let [tab (vec (repeatedly (* n n) l/lvar)) ;; n by n table of logic variables
rows (partition n tab) ;; rows of the table
cols (apply map vector rows) ;; columns of the table
points (fd/interval 0 (dec n))] ;; valid entries
(l/run num-of-sols [q]
@egri-nagy
egri-nagy / caesar_shift.clj
Created October 24, 2017 05:53
Caesar shift cipher
;; Caesar shift and its brute-force attack.
(def letters "abcdefghijklmnopqrstuvwxyz ")
(defn shift-map
"A hash-map that maps letters to letters cyclically shifted by n."
[n]
(zipmap letters
(take (count letters)
(drop n (cycle letters)))))
@egri-nagy
egri-nagy / b-w-t.clj
Last active October 20, 2017 13:51
Burrows-Wheeler Transform
;; simple implementation of the Burrows-Wheeler transform (used in bzip2)
;; https://en.wikipedia.org/wiki/Burrows-Wheeler_transform
(defn rotations
"All rotations (cyclic permutations) of a string s."
[s]
(let [n (count s)]
(reduce (fn [rotations i]
(conj rotations
(apply str
@egri-nagy
egri-nagy / destructuring_slope_of_a_line.clj
Last active April 8, 2017 04:03
Standard example of destructuring: calculating the slope of a line
; representation of a line defined by two points
(def l [[1 2] [2 4]])
;information extracted on demand, actual calculation obscure
(defn slope
[line]
(/
(- (first (first line)) (first (second line)))
(- (second (first line)) (second (second line)))))
@egri-nagy
egri-nagy / merge-sort-single-fn.clj
Created May 10, 2015 23:57
Merge sort in Clojure in a single function
(defn merge-sort
"sorting the given collection with merge-sort"
[coll]
(if (or (empty? coll) (= 1 (count coll)))
coll
(let [[l1 l2] (split-at (/ (count coll) 2) coll)]
;recursive call
(loop [r [] l1 (merge-sort l1) l2 (merge-sort l2)]
;merging
(cond (empty? l1) (into r l2) ;when l1 is exhausted