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

otus-04 hw #1

Closed
wants to merge 8 commits into from
Closed
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
64 changes: 52 additions & 12 deletions otus-04/src/otus_04/homework/magic_square.clj
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)})
Copy link

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))


(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)))
Copy link

Choose a reason for hiding this comment

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

Можно просто vec без скобок


Магический квадрат должен быть заполнен так, что суммы всех вертикалей,
горизонталей и диагоналей длиной в 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))))
Copy link

Choose a reason for hiding this comment

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

Хорошо, но многословно. Сравните, для примера, с вариантом

(defn magic-square [n]
  (let [sq (->> 0 (repeat n) vec (repeat n) vec)
        move (fn [sq [r c]]
               (let [norm (fn [x] (cond (< x 0) (dec n) (>= x n) 0 :else x))
                     rc' [(-> r dec norm) (-> c inc norm)]]
                 (if (zero? (get-in sq rc'))
                   rc'
                   [(-> r inc norm) c])))
        rc-start [0 (quot n 2)]]
    (loop [rc rc-start
           [i & is] (range 2 (inc (* n n)))
           sq (assoc-in sq rc-start 1)]
      (if-not i
        sq
        (let [rc' (move sq rc)]
          (recur rc' is (assoc-in sq rc' i)))))))

40 changes: 35 additions & 5 deletions otus-04/src/otus_04/homework/scramblies.clj
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)))
Copy link

Choose a reason for hiding this comment

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

Откройте для себя fnil : (update acc val (fnil inc 0))


(defn word->map
[word]
(reduce reducer {} word))
Copy link

Choose a reason for hiding this comment

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

Откройте для себя frequencies :)


(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)))
Copy link

Choose a reason for hiding this comment

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

Откройте для себя merge-with Итого весь код решения

(defn scramble? [letters word]
  (every? (comp not pos? second)
          (merge-with -
                      (frequencies word)
                      (frequencies (filter (set word) letters)))))

1 change: 1 addition & 0 deletions url-shortener/01-core/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# url-shortener
7 changes: 7 additions & 0 deletions url-shortener/01-core/project.clj
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})
44 changes: 44 additions & 0 deletions url-shortener/01-core/src/url_shortener/core.clj
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)))
Copy link

Choose a reason for hiding this comment

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

quot


(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

7 changes: 7 additions & 0 deletions url-shortener/01-core/test/url_shortener/core_test.clj
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))))