Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Created January 10, 2022 14:03
Show Gist options
  • Save ericnormand/87c7c0804b2cde1a1a1e65caaf4c5296 to your computer and use it in GitHub Desktop.
Save ericnormand/87c7c0804b2cde1a1a1e65caaf4c5296 to your computer and use it in GitHub Desktop.
458 PurelyFunctional.tv Newsletter

String difference

Imagine two strings, A and B. B is generated by shuffling the letters in A and adding a new random letter to it at a random position. Write a function that takes A and B and returns the new letter.

Examples

(diff "" "j") ;=> \j
(diff "a" "ab") ;=> \b
(diff "abc" "xcab") ;=> \x
(diff "xxyyzz" "xzyfyxz") ;=> \f
(diff "cccvv" "cvvcvc") ;=> \v

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 Jan 11, 2022

(defn diff [astr bstr]
  (loop [sa (sort astr) sb (sort bstr)]
    (if (= (first sa) (first sb))
      (recur (rest sa) (rest sb))
      (first sb))))

@miner
Copy link

miner commented Jan 11, 2022

(defn diff [a b]
  (reduce-kv (fn [_ c cnt] (when (odd? cnt) (reduced c)))
             nil
             (frequencies (str a b))))

@nwjsmith
Copy link

@miner I really like that concatenation/odd? trick

(defn diff
  [a b]
  (key (first (filter (comp odd? val) (frequencies (str a b))))))

@miner
Copy link

miner commented Jan 11, 2022

a transducer version, based on the bit-xor solution by @jonasseglare

(defn diff [before after]
  (transduce (map int)
             (completing bit-xor char)
             0
             (str before after)))

@filippocostalli
Copy link

(defn diff [s1 s2]
  (clojure.string/replace 
    (apply str (sort s2)) 
    (re-pattern (apply str (sort s1))) 
    "")) 

@KingCode
Copy link

(defn diff [a b]
  (let [fa (frequencies a) fb (frequencies b)]
    (->> b (some #(when (or (not (contains? fa %))
                            (not= (fa %) (fb %)))
                    %)))))

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