Skip to content

Instantly share code, notes, and snippets.

@tedpennings
Created November 17, 2011 02:06
Show Gist options
  • Save tedpennings/1372162 to your computer and use it in GitHub Desktop.
Save tedpennings/1372162 to your computer and use it in GitHub Desktop.
Hash table (sort of) in Clojure
(ns algorithms.hashtable)
; This is a programming assignment from my CS algorithms class.
(defn create-table [size]
(let [empty-table (hash-map)]
(loop [current 0
table empty-table]
(if (> size current)
(recur (inc current)
(assoc table current :empty))
table))))
(defn linear-hash [try value size]
(mod (+ value try) size))
(defn quadratic-hash [try value size]
(let [c1 1
c2 3
h (linear-hash 0 value size)]
(mod (+ h (* c1 try) (* c2 (* try try))) size)))
(defn double-hash [try value size]
(let [h1 (linear-hash 0 value size)
h2 (+ 1 (mod value (dec size))) ]
(mod (+ h1 (* try h2)) size)))
(defn insert [value table algorithm]
"Returns a modified view of the input table with the value inserted"
(loop [try 0]
(if (>= try (count table))
(throw (Exception. "Table full")))
(let [hash (algorithm try value (count table))]
(if (= :empty (table hash))
(assoc table hash value)
(recur (inc try))))))
(defn print-table [table]
"Prints a pretty version of the table"
(loop [keys (keys table)]
(if (seq keys)
(prn (str "Position " (first keys) " = " (table (first keys)))))
(if (seq keys)
(recur (next keys)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment