Last active
January 20, 2016 05:31
-
-
Save chenglou/b19737b2dced2288b7fc to your computer and use it in GitHub Desktop.
ClojureScript anagram implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; (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 |
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
looks awesome
I wonder what will come out if we don't have the
vals
calledthanks!