Advertisement
_eremec_

Untitled

Dec 10th, 2017
1,193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns lab3.core
  2.   (:require
  3.     [clojure.string :as str]))
  4.  
  5. (def text "С милым рай и в шалаше")
  6.  
  7. (defn padding [coll n sym right?]
  8.   (if right?
  9.       (concat coll (repeat (- n (count coll)) sym))
  10.       (concat (repeat (- n (count coll)) sym) coll)))
  11.  
  12. (defn split-text [text]
  13.  (map #(padding % 2 \space true) (partition-all 2 (seq text))))
  14.  
  15. (defn char->bin [ch n]
  16.   (padding (seq (Integer/toString (int ch) 2)) n \0 false))  
  17.  
  18. (defn bin->char [s]
  19.   (char (Integer/parseInt (apply str s) 2)))
  20.  
  21. (defn make-block [k [ch1 ch2]]
  22.   {:k k
  23.    :l (char->bin ch1 16)
  24.    :r (char->bin ch2 16)})
  25.  
  26. (defn bit-shift-r [s n]
  27.   (if (zero? n) s (recur (conj (drop-last s) (last s)) (dec n))))
  28.  
  29. (defn xor [s1 s2]
  30.   (map #(if (= %1 %2) \0 \1) s1 s2))
  31.  
  32. (defn new-key [k]
  33.   k)
  34.  
  35. (defn code-block [f {:keys [k l r]}]
  36.   {:k (new-key k) :l (xor (f l k) r) :r l})
  37.  
  38. (defn code-last [f {:keys [k l r]}]
  39.   {:k (new-key k) :l l :r (xor (f l k) r)})
  40.  
  41. (defn blocks->text [blocks]
  42.   (apply
  43.     str
  44.     (map (fn [{:keys [_ l r]}]
  45.            (str (bin->char l) (bin->char r)))
  46.          blocks)))
  47.  
  48. (defn swap-last [{:keys [k l r]}]
  49.   {:k k :l r :r l})
  50.  
  51. (defn encode [text n f k]
  52.   (loop [n n
  53.          blocks (map (partial make-block k) (split-text text))
  54.          ks (map (fn [_] (list k)) blocks)]
  55.     (if (zero? n)
  56.         [blocks ks]
  57.         (let [round-res (if (= n 1)
  58.                             (map (partial code-last f) blocks)
  59.                             (map (partial code-block f) blocks))
  60.               new-ks (map :k round-res)]
  61.           (recur
  62.             (dec n)
  63.             round-res
  64.             (map #(conj %1 %2) ks new-ks))))))
  65.  
  66. (defn decode [f [blocks ks]]
  67.   (loop [n (dec (count (first ks)))
  68.          blocks blocks
  69.          ks (map reverse ks)]
  70.     (if (zero? n)
  71.         (blocks->text (map swap-last blocks))
  72.         (recur
  73.           (dec n)
  74.           (map (partial code-block f) blocks)
  75.           (map rest ks)))))      
  76.  
  77. (def t1 (encode text 16 bit-shift-r 4))
  78. (println (blocks->text (first t1)))
  79. (def t2 (decode bit-shift-r t1))
  80. (println t2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement