Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

6 th homework #15

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions otus-01/src/otus/homework.clj
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
(ns otus.homework)


(defn solution "Add your solution as fuction body here" [])

(defn solution []
(double (/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5)))))
(* 3 (- 6 2) (- 2 7)))))
16 changes: 16 additions & 0 deletions otus-02/.joyride/deps.edn
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
;; clojure-lsp needs this config to analyze Joyride code
;; To tell clojure-lsp about this file:
;; 1. Add a source-alias to `.lsp/config.edn`. E.g.:
;; :source-aliases #{:src :test :joyride}
;; (The clojure-lsp defaults are `:src :test`.)
;; 2. Add a `:joyride` alias to the project root deps.edn file.
;; Minimal file content:
;; {:aliases {:joyride {:extra-deps {joyride/workspace {:local/root ".joyride"}}}}}
;;
;; To also tell clojure-lsp about your Joyride user scripts, see instructions
;; in your User Joyride config directory `deps.edn` file.
;; (`~/.config/joyride/deps.edn` on Mac/Linux, somewhere similar on Windows?)
{:deps {org.clojure/clojurescript {:mvn/version "1.11.54"}
funcool/promesa {:mvn/version "9.0.471"}
rewrite-clj/rewrite-clj {:mvn/version "1.1.46"}}
:paths ["src" "scripts"]}
2 changes: 1 addition & 1 deletion otus-02/project.clj
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

:resource-paths ["resources"]

:dependencies [[org.clojure/clojure "1.11.1"]]
:dependencies [[org.clojure/clojure "1.11.1"] [criterium "0.4.6"]]

:repl-options {:init-ns otus-02.core}

Expand Down
130 changes: 126 additions & 4 deletions otus-02/src/otus_02/homework/common_child.clj
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
(ns otus-02.homework.common-child)


;; Строка называется потомком другой строки,
;; если она может быть образована путем удаления 0 или более символов из другой строки.
;; Буквы нельзя переставлять.
Expand All @@ -15,8 +12,133 @@

;; Еще пример HARRY и SALLY. Ответ будет - 2, так как общий элемент у них AY

(ns otus-02.homework.common-child
(:require [criterium.core :as c]))

;; (defn assoc-in!
;; "Associates a value in a nested structure, where ks is a
;; sequence of keys and v is the new value and returns a new
;; nested structure. If any levels do not exist, hash-maps
;; will be created."
;; [m [k & ks] v]
;; (if ks
;; (assoc! m k (assoc-in! (get m k) ks v))
;; (assoc! m k v)))

;; Corrected Space-optimized DP solution
(defn longest-common-subsequence-length-space-optimized [^String s1 ^String s2]
(let [m (count s1)
n (count s2)
current-row (int-array (inc n))]
(doseq [i (range 1 (inc m))]
(let [previous-row (aclone current-row)]
(doseq [j (range 1 (inc n))]
(aset current-row j
(if (= (.charAt s1 (dec i)) (.charAt s2 (dec j)))
(inc (aget previous-row (dec j)))
(max (aget current-row (dec j))
(aget previous-row j)))))))
(aget current-row n)))

;; Corrected Iterative DP solution
(defn longest-common-subsequence-length-iterative [^String s1 ^String s2]
(let [m (count s1)
n (count s2)]
(loop [i 0
prev-row (vec (repeat (inc n) 0))]
(if (= i m)
(peek prev-row)
(recur (inc i)
(reduce
(fn [curr-row j]
(assoc curr-row j
(if (= (.charAt s1 i) (.charAt s2 (dec j)))
(inc (get prev-row (dec j)))
(max (get curr-row (dec j))
(get prev-row j)))))
(assoc prev-row 0 0)
(range 1 (inc n))))))))

;; Optimized vector-based solution
(defn longest-common-subsequence-length-optimized [^String s1 ^String s2]
(let [m (count s1)
n (count s2)
dp (atom (vec (repeat (inc m) (vec (repeat (inc n) 0)))))]
(doseq [i (range 1 (inc m))
j (range 1 (inc n))]
(let [char1 (.charAt s1 (dec i))
char2 (.charAt s2 (dec j))
new-val (if (= char1 char2)
(inc (get-in @dp [(dec i) (dec j)]))
(max (get-in @dp [(dec i) j]) (get-in @dp [i (dec j)])))]
(swap! dp assoc-in [i j] new-val)))
(get-in @dp [m n])))

;; Common child length function (wrapper for the chosen implementation)
(defn common-child-length [lcs-fn ^String s1 ^String s2]
(lcs-fn s1 s2))

;; Test function to verify correctness
(defn run-tests [lcs-fn]
(println "Running tests:")
(println "Test 1:" (= (common-child-length lcs-fn "SHINCHAN" "NOHARAAA") 3))
(println "Test 2:" (= (common-child-length lcs-fn "HARRY" "SALLY") 2))
(println "Test 3:" (= (common-child-length lcs-fn "AA" "BB") 0))
(println "Test 4:" (= (common-child-length lcs-fn "ABCDEF" "FBDAMN") 2)))

;; Run the tests with space-optimized version
(println "Testing with space-optimized version:")
(run-tests longest-common-subsequence-length-space-optimized)

;; Run the tests with iterative version
(println "\nTesting with iterative version:")
(run-tests longest-common-subsequence-length-iterative)

;; Run the tests with iterative version
(println "\nTesting with length-optimized version:")
(run-tests longest-common-subsequence-length-optimized)

;; Generate test data (unchanged)
(defn generate-random-string [length]
(apply str (repeatedly length #(char (+ (rand-int 26) 65)))))

(def small-s1 (generate-random-string 100))
(def small-s2 (generate-random-string 100))
(def medium-s1 (generate-random-string 1000))
(def medium-s2 (generate-random-string 1000))
(def large-s1 (generate-random-string 5000))
(def large-s2 (generate-random-string 5000))

(defn common-child-length [first-string second-string])
;; New function to measure memory usage
(defn measure-memory-usage []
(let [runtime (Runtime/getRuntime)]
(.gc runtime)
(Thread/sleep 100)
(.gc runtime)
(- (.totalMemory runtime) (.freeMemory runtime))))

;; Updated performance testing function with memory usage measurement
(defn run-performance-test [f s1 s2 description]
(println description)
(let [start-memory (measure-memory-usage)
_ (c/quick-bench (f s1 s2))
end-memory (measure-memory-usage)
memory-used (- end-memory start-memory)]
(println "Memory used:" (/ memory-used 1024 1024.0) "MB")))

;; Updated run-all-tests function
(defn run-all-performance-tests []
(run-performance-test longest-common-subsequence-length-space-optimized small-s1 small-s2 "Space-Optimized DP (Small)")
(run-performance-test longest-common-subsequence-length-iterative small-s1 small-s2 "Iterative DP (Small)")
(run-performance-test longest-common-subsequence-length-optimized small-s1 small-s2 "Optimized Vector (Small)")

(run-performance-test longest-common-subsequence-length-space-optimized medium-s1 medium-s2 "Space-Optimized DP (Medium)")
(run-performance-test longest-common-subsequence-length-iterative medium-s1 medium-s2 "Iterative DP (Medium)")
(run-performance-test longest-common-subsequence-length-optimized medium-s1 medium-s2 "Optimized Vector (Medium)")

(run-performance-test longest-common-subsequence-length-space-optimized large-s1 large-s2 "Space-Optimized DP (Large)")
(run-performance-test longest-common-subsequence-length-iterative large-s1 large-s2 "Iterative DP (Large)")
(run-performance-test longest-common-subsequence-length-optimized large-s1 large-s2 "Optimized Vector (Large)"))

;; Run the tests
(run-all-performance-tests)
26 changes: 25 additions & 1 deletion otus-02/src/otus_02/homework/palindrome.clj
Original file line number Diff line number Diff line change
@@ -1,6 +1,30 @@
(ns otus-02.homework.palindrome
(:require [clojure.string :as string]))

(def alphanumeric-pattern #"[a-zA-Z0-9\p{IsIdeographic}]")

(defn is-palindrome [test-string])
(defn alphanumeric? [c]
(boolean (re-matches alphanumeric-pattern (str c))))

(defn normalize-char [c]
(string/lower-case (str c)))

(defn is-palindrome [^String input]
(let [length (.length input)]
(loop [left 0
right (dec length)]
(cond
(>= left right) true

(not (alphanumeric? (.charAt input left)))
(recur (inc left) right)

(not (alphanumeric? (.charAt input right)))
(recur left (dec right))

:else
(let [left-char (normalize-char (.charAt input left))
right-char (normalize-char (.charAt input right))]
(if (= left-char right-char)
(recur (inc left) (dec right))
false))))))
16 changes: 11 additions & 5 deletions otus-02/src/otus_02/homework/pangram.clj
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
(ns otus-02.homework.pangram
(:require [clojure.string :as string]))


(defn is-pangram [test-string])
(ns otus-02.homework.pangram)

(defn is-pangram [^String input]
(loop [chars input
found-letters #{}]
(if (or (empty? chars) (= 26 (count found-letters)))
(= 26 (count found-letters))
(let [current-char (Character/toLowerCase (first chars))]
(if (and (>= (int current-char) (int \a))
(<= (int current-char) (int \z)))
(recur (rest chars) (conj found-letters current-char))
(recur (rest chars) found-letters))))))
34 changes: 30 additions & 4 deletions otus-02/src/otus_02/homework/square_code.clj
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
(ns otus-02.homework.square-code)
(ns otus-02.homework.square-code
(:require [clojure.string :as str]))

;; Реализовать классический метод составления секретных сообщений, называемый `square code`.
;; Выведите закодированную версию полученного текста.
Expand Down Expand Up @@ -48,9 +49,34 @@
"aohghn "
"sseoau "

(defn- normalize-string [^String input]
(-> input
str/lower-case
(str/replace #"[^\w]" "")))

(defn- calculate-dimensions [^String input]
(let [length (count input)
cols (int (Math/ceil (Math/sqrt length)))
rows (int (Math/ceil (/ length cols)))]
[rows cols]))

(defn encode-string [input])
(defn encode-string [^String input]
(let [normalized (normalize-string input)
[_ cols] (calculate-dimensions normalized)
chunks (partition-all cols normalized)
padded-chunks (map #(take cols (concat % (repeat \space))) chunks)]
(->> (apply map vector padded-chunks)
(map #(apply str %))
(str/join " "))))


(defn decode-string [input])
(defn decode-string [^String ciphertext]
(let [words (str/split ciphertext #"\s+")
cols (count words)
rows (apply max (map count words))
matrix (mapv #(vec (take rows (concat % (repeat \space)))) words)]
(->> (for [row (range rows)
col (range cols)
:let [char (get-in matrix [col row])]
:when (not= char \space)]
char)
(apply str))))
11 changes: 9 additions & 2 deletions otus-11/project.clj
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@
:url "http://example.com/FIXME"
:license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
:url "https://www.eclipse.org/legal/epl-2.0/"}
:dependencies [[org.clojure/clojure "1.10.3"]]
:test-paths ["test"]
:dependencies [[org.clojure/clojure "1.10.3"]
[org.clojure/test.check "1.1.0"]]

:repl-options {:init-ns otus-11.core})
:repl-options {:init-ns otus-11.core}

:main ^:skip-aot otus-11.id3v2-reader.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all
:jvm-opts ["-Dclojure.compiler.direct-linking=true"]}})
Loading