September 6, 2018

Just Juxt #23: Anagram Finder (4clojure #77)

Bow to Lord Dampnut

Write a function which finds all the anagrams in a vector of words. A word x is an anagram of word y if all the letters in x can be rearranged in a different order to form y. Your function should return a set of sets, where each sub-set is a group of words which are anagrams of each other. Each sub-set should have at least two words. Words without any anagrams should not be included in the result.

(ns live.test
  (:require [cljs.test :refer-macros [deftest is testing run-tests]]))
  
(defn anagram [c]
  (->> c
       (map (juxt sort identity))
       (group-by (comp str first))
       vals
       (filter #(> (count %) 1))
       (map #(set (map (fn [x] (second x)) %)))
       set))

(deftest anagram-test
  (is (= (anagram ["meat" "mat" "team" "mate" "eat"])
         #{#{"meat" "team" "mate"}}))
  (is (= (anagram ["veer" "lake" "item" "kale" "mite" "ever"])
         #{#{"veer" "ever"} #{"lake" "kale"} #{"mite" "item"}})))
  
(run-tests)
Tags: coding exercises KLIPSE 4clojure Cryogen juxt