Reputation: 53
I created a polynomial function that returns the string based representation of the terms of polynomial added together, however i was having difficulties in removing terms from the string that contain the 0 coefficient and its giving me a different output
Below is my function:
(defn format-poly [poly]
(clojure.string/join ""
(map-indexed (fn [index item] (cond
(= index 0) item
(= (get item 0) \-) item
:default (str "+" item)))
(reverse (for [[pow coeff] (map-indexed vector (rseq (:coefficients poly))) ; remove whatever is causing a negative coeff to be ignored
]
(cond
(= coeff 0) (remove zero? [pow coeff])
(= coeff 1) (format "%s^%d",(:variable poly) pow)
(= pow 0) (format "%s",coeff)
:else
(format "%d%s^%d" coeff (:variable poly) pow)))))))
sample input:
(format-poly {:variable "x"
:coefficients [1 0 0 2 3 4]})
Expected output: "x^6-2x^5+3x^4-4x^3+5x^2-6x^1+7"
Upvotes: 0
Views: 73
Reputation: 17859
i would propose gathering all the polynom print parts altogether into a flat collection, and then print all of them to string. Could look like this:
(defn format-poly [v coeffs]
(let [fmt-parts (mapcat (fn [coeff pow]
(when-not (zero? coeff)
[(if (neg? coeff) "-" "+")
(let [coeff (Math/abs coeff)]
(if (== 1 coeff) "" coeff))
(cond (zero? pow) ""
(== 1 pow) v
:else (str v "^" pow))]))
coeffs
(range (dec (count coeffs)) -1 -1))]
(apply str (if (= "+" (first fmt-parts))
(rest fmt-parts)
fmt-parts))))
user> (format-poly "x" [-1 -2 3 0 4 5])
;; "-x^5-2x^4+3x^3+4x+5"
user> (format-poly "x" [1 -2 3 0 4 5])
;; "x^5-2x^4+3x^3+4x+5"
user> (format-poly "x" [1 2 3 0 4 5])
;; "x^5+2x^4+3x^3+4x+5"
Upvotes: 2