-
Notifications
You must be signed in to change notification settings - Fork 8
Алексей Золотыx, домашнее задание №2 #20
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
base: main
Are you sure you want to change the base?
Changes from all commits
4bf434d
6bb5cdc
35d0a63
289084e
929209f
a6e674d
5e47012
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,17 @@ | ||
(ns otus-02.homework.palindrome | ||
(:require [clojure.string :as string])) | ||
|
||
(defn clean [test-string] | ||
(-> test-string | ||
(string/trim) | ||
(string/lower-case) | ||
(string/replace #"[\W]{1,}", ""))) | ||
|
||
(defn is-palindrome [test-string] | ||
(let [clean-string (clean test-string)] | ||
(= | ||
clean-string | ||
(string/reverse clean-string)))) | ||
|
||
|
||
(defn is-palindrome [test-string]) | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,14 @@ | ||
(ns otus-02.homework.pangram | ||
(:require [clojure.string :as string])) | ||
|
||
(def alphabet "abcdefghijklmnopqrstuvwxyz") | ||
|
||
(defn is-pangram [test-string]) | ||
(defn is-pangram [test-string] | ||
|
||
(= alphabet | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. вот тут опасно сравнивать со строкой. дело в том что множества это не упорядоченные коллекции и в зависимости от используемой хэш функции можно получить разный порядок элементов. множества всегда безопасней сравнивать с другими множествами |
||
(-> test-string | ||
(string/lower-case) | ||
(string/replace #"[\W]{1,}" "") | ||
(set) | ||
(string/join)))) | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,56 +1,48 @@ | ||
(ns otus-02.homework.square-code) | ||
(ns otus-02.homework.square-code | ||
(:require [clojure.math :as math] | ||
[clojure.string :as str])) | ||
|
||
(defn- pad-right [len val col] | ||
(take len (concat col (repeat val)))) | ||
|
||
(defn- get-col-width [input-string] | ||
(-> input-string | ||
(count) | ||
(math/sqrt) | ||
(math/ceil) | ||
(int))) | ||
|
||
(defn- prepare-str [input] | ||
(-> input | ||
(str/replace #"[\W]{1,}" "") | ||
(str/lower-case))) | ||
|
||
(defn- str->matrix [input] | ||
(let [len (get-col-width input)] | ||
(->> input | ||
(partition-all len) | ||
(map (fn [lst] (pad-right len " " lst)))))) | ||
|
||
(defn encode-string [input] | ||
(->> input | ||
(prepare-str) | ||
(str->matrix) | ||
(apply mapv str) | ||
(str/join " "))) | ||
|
||
(defn decode-string [ciphertext] | ||
(let [normalized (str/replace ciphertext #"([\w]{1,})([\W]{1,1})" "$1") | ||
length (count normalized) | ||
side (Math/sqrt length) | ||
rows (Math/floor side) | ||
cols (Math/ceil side)] | ||
(str/join | ||
(apply concat (for [i (range rows)] | ||
(for [j (range cols)] | ||
(let [value | ||
(get normalized | ||
(int (+ (* j rows) i)) | ||
"")] | ||
(when-not (= value \space) | ||
value)))))))) | ||
|
||
;; Реализовать классический метод составления секретных сообщений, называемый `square code`. | ||
;; Выведите закодированную версию полученного текста. | ||
|
||
;; Во-первых, текст нормализуется: из текста удаляются пробелы и знаки препинания, | ||
;; также текст переводится в нижний регистр. | ||
;; Затем нормализованные символы разбиваются на строки. | ||
;; Эти строки можно рассматривать как образующие прямоугольник при печати их друг под другом. | ||
|
||
;; Например, | ||
"If man was meant to stay on the ground, god would have given us roots." | ||
;; нормализуется в строку: | ||
"ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots" | ||
|
||
;; Разбиваем текст в виде прямоугольника. | ||
;; Размер прямоугольника (rows, cols) должен определяться длиной сообщения, | ||
;; так что c >= r и c - r <= 1, где c — количество столбцов, а r — количество строк. | ||
;; Наш нормализованный текст имеет длину 54 символа | ||
;; и представляет собой прямоугольник с c = 8 и r = 7: | ||
"ifmanwas" | ||
"meanttos" | ||
"tayonthe" | ||
"groundgo" | ||
"dwouldha" | ||
"vegivenu" | ||
"sroots " | ||
|
||
;; Закодированное сообщение получается путем чтения столбцов слева направо. | ||
;; Сообщение выше закодировано как: | ||
"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau" | ||
|
||
;; Полученный закодированный текст разбиваем кусками, которые заполняют идеальные прямоугольники (r X c), | ||
;; с кусочками c длины r, разделенными пробелами. | ||
;; Для фраз, которые на n символов меньше идеального прямоугольника, | ||
;; дополните каждый из последних n фрагментов одним пробелом в конце. | ||
"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau " | ||
|
||
;; Обратите внимание, что если бы мы сложили их, | ||
;; мы могли бы визуально декодировать зашифрованный текст обратно в исходное сообщение: | ||
|
||
"imtgdvs" | ||
"fearwer" | ||
"mayoogo" | ||
"anouuio" | ||
"ntnnlvt" | ||
"wttddes" | ||
"aohghn " | ||
"sseoau " | ||
|
||
|
||
|
||
(defn encode-string [input]) | ||
|
||
|
||
(defn decode-string [input]) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,23 @@ | ||
(ns otus-02.homework.fizzbuzz | ||
(:require | ||
[clojure.test :refer :all])) | ||
[clojure.test :refer :all] | ||
[clojure.math :as math])) | ||
|
||
; "Создайте программу, которая выводит числа от 1 до n. | ||
; - Если число делится на 3, выведите 'Fizz'; | ||
; - если число делится на 5, выведите 'Buzz'; | ||
; - если число делится и на 3 и на 5, выведите 'FizzBuzz'." | ||
; "implement me" | ||
|
||
(defn fizz-buzz [n] | ||
"Создайте программу, которая выводит числа от 1 до n. | ||
- Если число делится на 3, выведите 'Fizz'; | ||
- если число делится на 5, выведите 'Buzz'; | ||
- если число делится и на 3 и на 5, выведите 'FizzBuzz'." | ||
"implement me") | ||
|
||
(let [result | ||
(cond | ||
(= (rem n 3) 0) "Fizz" | ||
(= (rem n 5) 0) "Buzz" | ||
:else "FizzBuzz")] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. не верно указана ветка :else |
||
(println result) | ||
result)) | ||
|
||
(deftest fizz-buzz-test | ||
(is (= (fizz-buzz 10) | ||
'(1 2 "Fizz" 4 "Buzz" "Fizz" 7 8 "Fizz" "Buzz")))) | ||
"Buzz"))) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
очень элегантное решение 👍