Skip to content

Commit

Permalink
Straight line equation (#508)
Browse files Browse the repository at this point in the history
  • Loading branch information
solar05 committed Sep 2, 2020
1 parent a377794 commit bf9d876
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 27 deletions.
36 changes: 10 additions & 26 deletions src/battle_asserts/issues/straight_line_equation.clj
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,27 @@

(def description "Create a function to describe a line passing through
two points with coordinates (x1, y1) and (x2, y2).
General view of the equation of the line is `y = kx + b`.
If the line cannot be built, then an empty string should be returned.")
Return result as array where first number is `kx` and second number is `b`. Use floor rounding.")

(def signature
{:input [{:argument-name "first-point" :type {:name "array" :nested {:name "integer"}}}
{:argument-name "second-point" :type {:name "array" :nested {:name "integer"}}}]
:output {:type {:name "string"}}})
:output {:type {:name "array" :nested {:name "integer"}}}})

(defn arguments-generator
[]
(gen/tuple (gen/tuple gen/small-integer gen/small-integer)
(gen/tuple gen/small-integer gen/small-integer)))

(def test-data
[{:expected "y = 0.86x + 3.86"
:arguments [[6, 9], [-1, 3]]}
{:expected "y = 0.43x - 2.57"
:arguments [[6, 0], [-1, -3]]}
{:expected "y = - 0.50x + 1.00"
:arguments [[2, 0], [0, 1]]}
{:expected "y = 3.33x"
:arguments [[1.5, 5], [0, 0]]}
{:expected ""
:arguments [[0, 0], [0, 0]]}])
[{:expected [1 3] :arguments [[6 9] [1 4]]}
{:expected [0 -2] :arguments [[6 0] [-1 -3]]}
{:expected [-5 10] :arguments [[2 0] [0 10]]}
{:expected [3 0] :arguments [[1.5 5] [0 0]]}])

(defn solution [[x1, y1], [x2, y2]]
(letfn [(format-b [num] (cond
(zero? num) ""
(neg? num) (format " - %.2f" (* -1 num))
:else (format " + %.2f" num)))
(format-k [num] (cond
(zero? num) " x"
(neg? num) (format " - %.2fx" (* -1 num))
:else (format " %.2fx" num)))
(k [x1, x2, y1, y2] (float (/ (- y1 y2) (- x1 x2))))
(zero-division-protected? [x1, x2, y1, y2] (not (or (zero? (- y1 y2)) (zero? (- x1 x2)))))]
(if (zero-division-protected? x1 x2 y1 y2)
(str "y =" (format-k (k x1 x2 y1 y2)) (format-b (- y2 (* (k x1 x2 y1 y2) x2))))
"")))
(letfn [(k [x1, x2, y1, y2] (float (/ (- y1 y2) (- x1 x2))))]
(let [first-part (int (k x1 x2 y1 y2))
second-part (int (- y2 (* (k x1 x2 y1 y2) x2)))]
[first-part second-part])))

4 changes: 3 additions & 1 deletion test/battle_asserts/issues/straight_line_equation_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
(ct/defspec spec-solution
20
(prop/for-all [v (issue/arguments-generator)]
(string? (apply issue/solution v))))
(try
(vector? (apply issue/solution v))
(catch ArithmeticException e true))))

(deftest test-solution
(h/generate-tests issue/test-data issue/solution))

0 comments on commit bf9d876

Please sign in to comment.