Last active
December 14, 2015 00:39
-
-
Save MarcoPolo/5000557 to your computer and use it in GitHub Desktop.
new stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;Fixed indentation | |
(defn range-char [start end] | |
(let [ i (int start) | |
j (inc (int end))] | |
(map char (range i j)))) | |
;Fixed indentation | |
(defn shift-list [coll n] ;; You don't need to do seq unless you are testing if a seq is empty or changing data structs | |
(flatten | |
(reverse (split-at n coll)))) | |
;Fixed indentation | |
(defn caesar-cipher [ciphertext shift] | |
(let [ alphabet (range-char \a \z) | |
cipher (shift-list alphabet shift) | |
lookup-table (zipmap alphabet cipher) | |
translate-char #(lookup-table % \_)] ;; You don't need to use get on a hash-map you can use it like a function with the 2nd arg being the "not found" value | |
(apply str | |
(map translate-char ciphertext)))) | |
(caesar-cipher "ftkvhblvhhe" 7) | |
;; Fixed indention in the let you want the values you are setting to line up on the left margin | |
(let [ cipher-shift 2 | |
ciphertext (slurp "puzzle1.txt") | |
plain-text (caesar-cipher ciphertext cipher-shift)] | |
(println plain-text)) | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
;; I rewrote it to how I would do it now | |
(def char-range (inc (- (int \z) (int \a)))) | |
;; This function can stand on its own and be perfectly happy | |
(defn normalize-char [character] | |
(- (int character) (int \a))) | |
;; The function just shifts the letter using mod making use of the normalize fn above | |
(defn decode-char [shift character] | |
(let [ shifted-char (+ shift (normalize-char character))] | |
(char (+ (mod shifted-char char-range) | |
(int \a))))) | |
(let [ cipher-shift 7 | |
cipher-text "ftkvhblvhhe"] | |
;; Demo the threading macro | |
;; This tells it to eval to first expression and put it at the end of the arg list in the proceeding expressions | |
(->> | |
;; We use a partial so we can create a new function with the cipher shift value inside the closure | |
(map (partial decode-char cipher-shift) cipher-text) | |
;; Use apply to convert (str [ \a \b \c ] ) to (str \a \b \c) | |
(apply str))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment