Skip to content

Instantly share code, notes, and snippets.

@chenglou
Last active January 20, 2016 05:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chenglou/b19737b2dced2288b7fc to your computer and use it in GitHub Desktop.
Save chenglou/b19737b2dced2288b7fc to your computer and use it in GitHub Desktop.
ClojureScript anagram implementation
; (group-by f list): call f on each item in list. The return value becomes a key
; of the resulting map, whose keys map to the list of items for which f returned
; that key.
; (vals map): returns a list of the values of the map.
(defn anagram [words] (vals (group-by sort words)))
(= (anagram ["star" "rats" "car" "arc" "stars"])
[["star" "rats"] ["car" "arc"] ["stars"]]) ; true
@zzz6519003
Copy link

looks awesome
I wonder what will come out if we don't have the vals called

thanks!

@zzz6519003
Copy link

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]


# @param {String[]} strs
# @return {String[][]}
def group_anagrams(strs)
  strs.inject(Hash.new([])) do |h, s|
    h[s.chars.sort.join] += [s]
    h
  end.map{|k, v| v.sort}
end

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