Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ pom.xml.asc
.hg/
.clj-kondo
.calva
.lsp
.lsp
.DS_Store
14 changes: 13 additions & 1 deletion otus-02/src/otus_02/homework/common_child.clj
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,16 @@
;; Еще пример HARRY и SALLY. Ответ будет - 2, так как общий элемент у них AY


(defn common-child-length [fist-string second-string])
(defn common-child-length [first-string second-string]
(cond
(or (empty? first-string) (empty? second-string)) 0
(= (last first-string) (last second-string))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хорошее решение
один вопрос - почему сравнение ведётся с конца строки используя last?
кажется что можно сделать тоже самое но начать с начала используя first в таком случае не прийдётся находить длину строки и вычитать единицу (- (count second-string) 1)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне показалось, что это наилучшее решение с точки зрения динамического программирования, не нужно использовать лишнюю память.
Теперь, понимая особенности recur и вчерашнюю дискуссию по поводу last, понимаю, что оптимальней было создать структуру под матрицу значений и заполнять ее с начала

( + 1 (common-child-length
(subs first-string 0 (- (count first-string) 1))
(subs second-string 0 (- (count second-string) 1))))
:else (max (common-child-length first-string
(subs second-string 0 (- (count second-string) 1)))
(common-child-length (subs first-string 0 (- (count first-string) 1))
second-string))
))

14 changes: 12 additions & 2 deletions otus-02/src/otus_02/homework/palindrome.clj
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
(ns otus-02.homework.palindrome)
(ns otus-02.homework.palindrome
(:require [clojure.string :as s]))
Copy link
Collaborator

@margintop15px margintop15px May 15, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это не ошибка, а скорее совет на будущее - одно или дву буквенные алиасы не рекомендуется использовать так как в будущем будет тяжело понять что это значит
в данном случае можно использовать string в качестве алиаса


(def alphabet (set "abcdefghijklmnopqrstuvwxyz"))

(defn normalize-str [s-not-normal]
(filter some?
(map alphabet
Comment on lines +7 to +8
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хороший вариант с сетом и фильтрацией
еще есть вариант с использованием clojure.string/replace
(s/replace (s/lower-case s-not-normal) #"[^a-z]" "")
регулярка #"[^a-z]" сматчится на всё кроме букв

(s/lower-case s-not-normal))))

(defn is-palindrome [test-string]
(= (normalize-str test-string)
(normalize-str (s/reverse test-string))))

(defn is-palindrome [test-string])
9 changes: 7 additions & 2 deletions otus-02/src/otus_02/homework/pangram.clj
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
(ns otus-02.homework.pangram)
(ns otus-02.homework.pangram
(:require [otus-02.homework.palindrome :refer [normalize-str, alphabet]]))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

запятые можно не ставить clojure их игнорирует, но если вам так удобнее то можно ставить

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это старая привычка - запятые :)



(defn is-pangram [test-string])

(defn is-pangram [test-string]
(= alphabet
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

(set (normalize-str test-string))))

37 changes: 34 additions & 3 deletions otus-02/src/otus_02/homework/square_code.clj
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
(ns otus-02.homework.square-code)
(ns otus-02.homework.square-code
(:require [otus-02.homework.palindrome :refer [normalize-str]]
[clojure.string :as s]))

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

(defn size-field [len-str]
(let [x (int (Math/sqrt len-str))]
(cond
(= len-str (* x x)) [x x]
(<= len-str (* x (inc x))) [(inc x) x]
:else [(inc x) (inc x)])))



(defn encode-string [input])
(defn mix [v r]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

еще совет на будущее про имена - лучше использовать длинные понятные слова в качестве имен. через месяц уже обычно трудно вспомнить что это значило

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Спасибо за это замечание. Я с Вами согласен, но старался следовать соглашению о стиле https://github.com/bbatsov/clojure-style-guide#idiomatic-names
Возможно я его приватно истолковал

(for [i (range r)]
(map #(nth % i "") v)))

(defn l->str [l]
(map #(apply str %) l)
)

(defn decode-string [input])
(defn encode-string [input]
(let [n-input (normalize-str input)
[r _] (size-field (count n-input))
v-input (partition r r (cycle " ") n-input)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

отлично что использовали cycle

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Буду честен, просто утянул с интернета. Мне нужна была бесконечная последовательность пробелов. :)

l-mix (mix v-input r)
s-mix (l->str l-mix)]
(s/join " " s-mix)))

(encode-string "If man was meant to stay on the ground, god would have given us roots.")

(defn decode-string [input]
(let [l-input (s/split input #" ")
r (count (get l-input 0))
v-input (mix l-input r)
s-input (l->str v-input)]
(apply str (normalize-str (s/join s-input)))))

(decode-string "imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau ")