Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Last active May 27, 2022 20:55
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ericnormand/a3489d47e163d84650a7c2f5ff32ecd6 to your computer and use it in GitHub Desktop.
460 PurelyFunctional.tv Newsletter

NOTE: If you're looking for issue 461 (Primes in a number), please go here: https://gist.github.com/ericnormand/d52d1fe0e80f06e4b517d45a082765a0

Rearrange sentence

Here's a neat, yet contrived, text processing problem. The words in your sentence have been mixed up. Luckily, there's a number embedded in each word that says its position in the sentence. Write a function that puts the words in the right order and removes the position digits.

Examples

(rearrange "World2! He1llo,") ;=> "Hello, World!"
(rearrange "fo3r 5more Elegan1t 2weapons age.7 civil6ized a4") ;=> "Elegant weapons for a more civilized age."
(rearrange "") ;=> ""

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://purelyfunctional.tv/newsletter/

@miner
Copy link

miner commented Feb 5, 2022

;; assuming single digit per word
(defn rearrange [sentence]
  (->> (str/split sentence #" ")
       (reduce (fn [sm word] (assoc sm (re-find  #"\d" word) (str/replace word #"\d" "")))
               (sorted-map))
       vals
       (str/join " ")))

;; allow multiple consecutive digits
(defn rearrange2 [sentence]
  (->> (str/split sentence #" ")
       (reduce (fn [sm word]
                 (assoc sm
                        (Long/parseLong (or (re-find  #"\d+" word) "0"))
                        (str/replace word #"\d+" "")))
               (sorted-map))
       vals
       (str/join " ")))

@KingCode
Copy link

(def re #"([^\d]*)(\d+)([^\d]*)")

(defn n+word [word]
  (let [[pfx number sfx] (->> word (re-matches re) rest)]
    [(Integer/parseInt number) (str pfx sfx)]))

(defn rearrange [sentence]
  (let [order->w  (->> (clojure.string/split sentence #"\s+")
                       (into (sorted-map) 
                             (comp
                              (filter seq)
                              (map #(n+word %)))))]
    (->> order->w vals (interpose " ") (apply str))))

(rearrange "World2! He1llo,") ;=> "Hello, World!"
(rearrange "fo3r 5more Elegan1t 2weapons age.7 civil6ized a4")
;=> "Elegant weapons for a more civilized age."
(rearrange "") ;=> ""

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