Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Last active June 7, 2022 17:49
Show Gist options
  • Save ericnormand/66a3ddaafc7c61dcb0a857aa88239142 to your computer and use it in GitHub Desktop.
Save ericnormand/66a3ddaafc7c61dcb0a857aa88239142 to your computer and use it in GitHub Desktop.
470 Eric Normand Newsletter

Reverse words

Write a function that takes a string containing words (one or more sentences) and returns a string containing the words in reverse order.

Examples

(reverse-words "my name is Eric.") ;;=> "Eric. is my name"
(reverse-words "hello") ;;=> "hello"
(reverse-words "I love you") ;;=> "you love I"

Note: Words are characters separated by whitespace.

Thanks to this site for the problem idea, where it is rated Very Hard in Java. The problem has been modified.

Please submit your solutions as comments on this gist.

To subscribe: https://ericnormand.me/newsletter

@KingCode
Copy link

KingCode commented Jun 2, 2022

Here is a little variant which preserves white space between tokens.
EDIT @jonasseglare, I like your solution which also preserves spacing, but has a simpler approach (no corner cases, unlike mine).

Also thanks to @miner for the rseq comment, I started using it. From the documentation, it looks like the trade-off b/w reverse/rseq is convenience vs performance, as reverse seems to allow any seqable including regular vanilla maps, and rseq requires a sorted structure (actually a reversible?, but most/all sorted? implementations also implement clojure.lang.Reversible). Fun stuff!

(require '[clojure.string :refer [split]])

(defn reverse-words [txt]
  (let [rspaces (-> txt (split #"[^\s]+") rest reverse (conj "")) 
        rwords (->> (split txt #"\s+") rseq)]
    (->> rwords (interleave rspaces) (apply str))))


(reverse-words "my name is Eric.") ;;=> "Eric. is name my"
(reverse-words "hello") ;;=> "hello"
(reverse-words "I love you") ;;=> "you love I"
(reverse-words "I,  love you");;=>"you love  I,"

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