-
Notifications
You must be signed in to change notification settings - Fork 4
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
otus-04 hw #1
otus-04 hw #1
Changes from all commits
96a7df8
200109a
dd8709b
4731516
eb8eea9
08e06e8
429b3f9
cda0c91
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,17 +1,57 @@ | ||
(ns otus-04.homework.magic-square) | ||
|
||
;; Оригинальная задача: | ||
;; https://www.codewars.com/kata/570b69d96731d4cf9c001597 | ||
;; | ||
;; Подсказка: используйте "Siamese method" | ||
;; https://en.wikipedia.org/wiki/Siamese_method | ||
(defn next-index-row-factory | ||
[n] | ||
(fn [index] (if (= index 0) (dec n) (dec index)))) | ||
|
||
(defn magic-square | ||
"Функция возвращает вектор векторов целых чисел, | ||
описывающий магический квадрат размера n*n, | ||
где n - нечётное натуральное число. | ||
(defn next-index-col-factory | ||
[n] | ||
(fn [index] (if (= index (dec n)) 0 (inc index)))) | ||
|
||
(defn next-coords | ||
[next-index-col next-index-row {:keys [col row]}] | ||
{:row (next-index-row row) | ||
:col (next-index-col col)}) | ||
|
||
(defn build-square-map | ||
[square-map coords next-coords-fn value square-size] | ||
(if (zero? square-size) | ||
square-map | ||
(let [new-value (inc value) | ||
next-map (assoc square-map coords new-value) | ||
next-coords (next-coords-fn coords) | ||
cell-empty? (nil? (get next-map next-coords)) | ||
next-coords (if cell-empty? next-coords {:row (inc (:row coords)) :col (:col coords)})] | ||
|
||
(build-square-map next-map next-coords next-coords-fn new-value (dec square-size))))) | ||
|
||
(defn repeat-n-vec | ||
[item n] | ||
(->> item | ||
(repeat n) | ||
(vec))) | ||
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. Можно просто |
||
|
||
Магический квадрат должен быть заполнен так, что суммы всех вертикалей, | ||
горизонталей и диагоналей длиной в n должны быть одинаковы." | ||
(defn empty-square-vec | ||
[n] | ||
[[0]]) | ||
(repeat-n-vec (repeat-n-vec nil n) n)) | ||
|
||
(defn magic-square | ||
[n] | ||
{:pre [(odd? n)]} | ||
|
||
(let [initial-index (quot n 2) | ||
initial-coords {:row 0 :col initial-index} | ||
initial-value 0 | ||
next-index-col (next-index-col-factory n) | ||
next-index-row (next-index-row-factory n) | ||
next-coords-fn (partial next-coords next-index-col next-index-row) | ||
empty-vec (empty-square-vec n) | ||
square-map (build-square-map {} initial-coords next-coords-fn initial-value (* n n))] | ||
|
||
(reduce (fn [acc {:keys [row col] :as val}] | ||
(let [square-val (get square-map val) | ||
square-row (nth acc row) | ||
new-row (assoc square-row col square-val)] | ||
|
||
(assoc acc row new-row))) | ||
empty-vec (keys square-map)))) | ||
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. Хорошо, но многословно. Сравните, для примера, с вариантом
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,40 @@ | ||
(ns otus-04.homework.scramblies) | ||
|
||
;; Оригинальная задача: | ||
;; https://www.codewars.com/kata/55c04b4cc56a697bb0000048 | ||
;; 1-st attempt | ||
;; первая попытка не учитывала что в letters может быть не достаточно букв для | ||
;; построения word | ||
(defn scramble? | ||
[letters word] | ||
(let [letters-set (set letters)] | ||
(every? true? | ||
(map (comp not nil? letters-set) word)))) | ||
|
||
;; 2-nd attempt | ||
;; вторая попытка учитывает кол-во букв, но результат получаем двумя проходами по | ||
;; последовательности ключей, решил заменить на один проход при помощи reduce | ||
(defn reducer [acc val] | ||
(if (acc val) | ||
(update acc val inc) | ||
(assoc acc val 1))) | ||
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. Откройте для себя |
||
|
||
(defn word->map | ||
[word] | ||
(reduce reducer {} word)) | ||
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. Откройте для себя |
||
|
||
(defn scramble? | ||
"Функция возвращает true, если из букв в строке letters | ||
можно составить слово word." | ||
[letters word] | ||
nil) | ||
(let [letters-map (word->map letters) | ||
word-map (word->map word) | ||
word-map-keys (keys word-map)] | ||
|
||
(every? false? | ||
(map #(< (letters-map %1 0) (word-map %1 0)) word-map-keys)))) | ||
|
||
;; 3-rd attempt | ||
(defn scramble? | ||
[letters word] | ||
(let [letters-map (word->map letters) | ||
word-map (word->map word) | ||
word-map-keys (keys word-map)] | ||
|
||
(reduce #(if (< (letters-map %2 0) (word-map %2 0)) (not %1) %1) true word-map-keys))) | ||
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. Откройте для себя
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# url-shortener |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
(defproject url-shortener "0.1.0-SNAPSHOT" | ||
:description "FIXME: write description" | ||
: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.12.0"]] | ||
:repl-options {:init-ns url-shortener.core}) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
(ns url-shortener.core | ||
(:require [clojure.string :as string])) | ||
|
||
;; Consts | ||
(def ^:const alphabet-size 62) | ||
|
||
(def ^:const alphabet | ||
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") | ||
|
||
;; Logic | ||
(defn- get-idx [i] | ||
(Math/floor (/ i alphabet-size))) | ||
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.
|
||
|
||
(defn- get-character-by-idx [i] | ||
(get alphabet (rem i alphabet-size))) | ||
|
||
(defn int->id [id] | ||
(if (< id alphabet-size) | ||
(str (get-character-by-idx id)) | ||
(let [codes (->> (iterate get-idx id) | ||
(take-while pos?) | ||
(map get-character-by-idx))] | ||
(string/join (reverse codes))))) | ||
|
||
(comment | ||
(int->id 0) ; => "0" | ||
(int->id alphabet-size) ; => "10" | ||
(int->id 9999999999999) ; => "2q3Rktod" | ||
(int->id Long/MAX_VALUE)) ; => "AzL8n0Y58W7" | ||
|
||
|
||
(defn id->int [id] | ||
(reduce (fn [id ch] | ||
(+ (* id alphabet-size) | ||
(string/index-of alphabet ch))) | ||
0 | ||
id)) | ||
|
||
(comment | ||
(id->int "0") ; => 0 | ||
(id->int "z") ; => 61 | ||
(id->int "clj") ; => 149031 | ||
(id->int "Clojure")) ; => 725410830262 | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
(ns url-shortener.core-test | ||
(:require [clojure.test :refer :all] | ||
[url-shortener.core :refer :all])) | ||
|
||
(deftest a-test | ||
(testing "FIXME, I fail." | ||
(is (= 0 1)))) |
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.
Вопрос вкуса, можно еще
(-> m (update :row next-index-row) (update :col next-index-col))