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

hw-01 #3

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
59 changes: 57 additions & 2 deletions otus-02/src/otus_02/homework/common_child.clj
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
(ns otus-02.homework.common-child)


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

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

; (defn lol [n]
; (loop [i 0 r nil]
; (if (> i n)
; r
; (loop [j 0 s nil]
; (if (< j n) (recur (+ 1 j) (conj s [i j])) s)))))
Copy link

Choose a reason for hiding this comment

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

inc is more idiomatic than (+ 1 .. but it's a style case

;
; (lol 10)
;
; (defn look [s1 s2 i j t]
; (let
; [s1-elem (nth s1 (- i 1))
; s2-elem (nth s2 (- j 1))
; i-1j-1 (get-in t [(- i 1) (- j 1)])
; i-1j (get-in t [(- i 1) j])
; ij-1 (get-in t [i (- j 1)])]
; (if (= s1-elem s2-elem) (assoc-in t [i j] (+ i-1j-1 1)) (assoc-in t [i j] (max i-1j ij-1)))))
;
; (get-in [[0,0,0,0,0,0], [0],[0],[0],[0],[0],[0]] [1 0])
; (assoc-in [[0,0,0,0,0,0], [0],[0],[0],[0],[0],[0]] [1 1] 12)
;
; (assoc-in [[0,0,0,0,0,0], [0],[0],[0],[0],[0],[0]] [2 1] 1)
;
; (range 1 (+ 2 (count "HARRY")))
;
; (def i1 (look "HARRY" "SALLY" 1 1 [[0,0,0,0,0,0], [0], [0], [0], [0], [0], [0], [0]]))
; (def i2 (look "HARRY" "SALLY" 1 2 i1))
; (def i3 (look "HARRY" "SALLY" 1 3 i2))
; (def i4 (look "HARRY" "SALLY" 1 4 i3))
; (def i5 (look "HARRY" "SALLY" 1 5 i4))
;
; (def i6 (look "HARRY" "SALLY" 2 1 i5))
; (def i7 (look "HARRY" "SALLY" 2 2 i6))
; (def i8 (look "HARRY" "SALLY" 2 3 i7))
; (def i9 (look "HARRY" "SALLY" 2 4 i8))
; (def i10 (look "HARRY" "SALLY" 2 5 i9))
;
; (def q (vec (repeat (+ 1 (count "HARRY")) 0)))
; (def w (vec (repeat (+ 1 (count "SALLY")) [0])))
; (def e (vec (concat q w)))


(defn common-child-length [first-string second-string])
(defn common-child-length [s1 s2]
(let [look (fn [s1 s2 i j t]
(let
[s1-elem (nth s1 (- i 1))
s2-elem (nth s2 (- j 1))
i-1j-1 (get-in t [(- i 1) (- j 1)])
i-1j (get-in t [(- i 1) j])
ij-1 (get-in t [i (- j 1)])]
(if (= s1-elem s2-elem) (assoc-in t [i j] (+ i-1j-1 1)) (assoc-in t [i j] (max i-1j ij-1)))))
t [(vec (repeat (+ 1 (count s1)) 0))]
r (vec (repeat (+ 1 (count s2)) [0]))
table (vec (concat t r))
Copy link

Choose a reason for hiding this comment

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

You may use maps instead of vectors for DP, and then you don't need to prefill it by zeros, all getters has variants with defaults (get-in {} [1 2] 33) => 33

irange (range 1 (+ 1 (count s1)))
jrange (range 1 (+ 1 (count s2)))]
(get-in (reduce (fn [t i] (reduce (fn [t1 j] (look s1 s2 i j t1)) t jrange)) table irange) [(count s1) (count s1)])))

(common-child-length "SHINCHAN" "NOHARAAA")


27 changes: 25 additions & 2 deletions otus-02/src/otus_02/homework/palindrome.clj
Original file line number Diff line number Diff line change
@@ -1,6 +1,29 @@
(ns otus-02.homework.palindrome
(:require [clojure.string :as string]))
(:require [clojure.string :as string]
[clojure.string :as str]))

(defn remove-non-alpha [s]
(apply str (re-seq #"[a-zA-Z]+" s)))

(defn is-palindrome [test-string])

(defn aux [s len pos]
(cond
(>= pos len) true
(= (nth s pos) (nth s (- len pos))) (aux s len (+ 1 pos))
Copy link

Choose a reason for hiding this comment

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

There is no such thing as TCO in Clojure, so recur would be better

:else false))

(defn is-palindrome [test-string]
(let [
s (-> test-string remove-non-alpha str/lower-case)
len (- (count s) 1)
]
(aux s len 0)

)
)

(-> "Was it a cat I saw?" remove-non-alpha str/lower-case )


(is-palindrome "Was it a cat I saw?")
(print 21)
15 changes: 13 additions & 2 deletions otus-02/src/otus_02/homework/pangram.clj
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
(ns otus-02.homework.pangram
(:require [clojure.string :as string]))
(:require [clojure.string :as string]
[clojure.string :as str]))
Copy link

Choose a reason for hiding this comment

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

Bad practice, just one import for 1 ns

(require '[clojure.string :as str])

(def letters
[\a \b \c \d \e \f \g \h \i \j \k \l \m \n \o \p \q \r \s \t \u \v \w \x \y \z])
Copy link

Choose a reason for hiding this comment

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

(vec "abcdefghijklmnopqrstuvwxyz") :)


(defn is-pangram [test-string])
(def chars-set (set (map char (range (int \a) (+ (int \a) 26)))))

(defn is-pangram [test-string]
(>= (count (reduce (fn [a e] (conj a e)) (set []) (str/lower-case test-string))) 26)
Copy link

Choose a reason for hiding this comment

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

(fn [a e] (conj a e)) == conj :)
(set []) == #{} :)
(reduce (fn [a e] (conj a e)) (set []) xxx) == (set xxx) :)))

PS: you'll reduce all the string, even if it's already pangram on it's first 2%
PPS: "0123456789!@#$%^&*()_+|~<>,." will be pangram by your code :)


)

(is-pangram "The quick brown fox jumps over the lazy dog")

36 changes: 29 additions & 7 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
[clojure.string :as str]))

;; Реализовать классический метод составления секретных сообщений, называемый `square code`.
;; Выведите закодированную версию полученного текста.
Expand All @@ -11,8 +13,8 @@
;; Например,
"If man was meant to stay on the ground, god would have given us roots."
;; нормализуется в строку:
"ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots"

(def s "ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots")
;; Разбиваем текст в виде прямоугольника.
;; Размер прямоугольника (rows, cols) должен определяться длиной сообщения,
;; так что c >= r и c - r <= 1, где c — количество столбцов, а r — количество строк.
Expand All @@ -26,6 +28,31 @@
"vegivenu"
"sroots "

(defn remove-spaces [s]
(apply str (remove #(= % \space) s)))

(defn normalize-text [text]
(-> text
(clojure.string/replace #"\s+|\p{Punct}" "")
clojure.string/lower-case))
Copy link

Choose a reason for hiding this comment

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

str/lower-case. You already imported qualified ns on line 3 of this file


(defn encode-string [input]
(let [s (normalize-text input)
n (+ 1 (int (Math/floor (Math/sqrt (double (count s))))))
rows (partition n n nil s)
transposed (map (fn [i] (map #(nth % i \space) rows)) (range n))
res3 (clojure.string/join " " (map (fn [elem] (apply str (map str elem))) transposed))]
res3))

(defn decode-string [s]
(let [a (remove clojure.string/blank? (clojure.string/split s #" "))
n (count (first a))
transposed (map (fn [i] (map #(nth % i \space) a)) (range n))
res (remove-spaces (apply str (map (fn [elem] (apply str (map str elem))) transposed)))]
res))

Copy link

Choose a reason for hiding this comment

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

It may work, but.... Looks like you try to use imperative algorithms with mutable state in a case of Clojure, where we prefer immutable data and functional way.
Hope we'll discuss it on Q&A stream

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

;; Закодированное сообщение получается путем чтения столбцов слева направо.
;; Сообщение выше закодировано как:
"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau"
Expand All @@ -49,8 +76,3 @@
"sseoau "



(defn encode-string [input])


(defn decode-string [input])
9 changes: 8 additions & 1 deletion otus-02/test/otus_02/homework/fizzbuzz.clj
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,21 @@
(:require
[clojure.test :refer :all]))

(defn is-divisible [n by]
(zero? (mod n by)))

(defn fizz-buzz [n]
"Создайте программу, которая выводит числа от 1 до n.
- Если число делится на 3, выведите 'Fizz';
- если число делится на 5, выведите 'Buzz';
- если число делится и на 3 и на 5, выведите 'FizzBuzz'."
"implement me")
(map (fn [e] (cond
(is-divisible e 15) "FizzBuzz"
(is-divisible e 5) "Buzz"
(is-divisible e 3) "Fizz" :else e)
) (range 1 (+ 1 n))))

(fizz-buzz 10)

(deftest fizz-buzz-test
(is (= (fizz-buzz 10)
Expand Down