Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Created February 9, 2021 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericnormand/bf1178a04c7b28cdaf26e0fb3257defe to your computer and use it in GitHub Desktop.
Save ericnormand/bf1178a04c7b28cdaf26e0fb3257defe to your computer and use it in GitHub Desktop.
413 - PurelyFunctional.tv Newsletter

Minimum steps to palindrome

A string is a palindrome if it is equal to its reverse.

(= "racecar" (str/reverse "racecar")) ;=> true, so palindrome

Your task is to write a function that adds a minimum of letters to the end of a string to make it a palindrome.

Examples

(->palindrome "race") ;=> "racecar"
(->palindrome "mad") ;=> "madam"
(->palindrome "mirror") ;=> "mirrorrim"

Note: the generated string does not have to be a real English word.

Thanks to this site for the challenge idea where it is considered Expert in JavaScript. The problem has been modified from the original.

Please submit your solutions as comments on this gist.

@dfuenzalida
Copy link

dfuenzalida commented Feb 15, 2021

A little late to this one, but similar to the others above:

(defn palin? [s]
  (= (seq s) (reverse s)))

(defn ->palindrome [s]
  (->> s reverse rest (reductions str s) (filter palin?) first))

;; (->palindrome "race") ;; => "racecar"
;; (->palindrome "mad") ;; => "madam"
;; (->palindrome "mirror") ;; => "mirrororrim"

@RedPenguin101
Copy link

(defn ->palindrome [string]
  (->> (range 1 (count string))
       (map #(str string (str/reverse (subs string 0 %))))
       (some #(#{%} (str/reverse %)))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment