Hello all
i need to do some thing like that in the dictionary
Dict(314 => ["ate","eat","tea"],311 => ["bat"],323 => ["nat","tan"])
iand this is my code
function groupAnagrams(str)
**d = Dict{Int64,Array{String,1}}() # her i try to do Vector{String}[] , didn't work**
for i =1:length(str)
count = 0
for j=1:length(str[i])
count +=Int(str[i][j])
end
if !haskey(d,count)
d[count ] = str[i]
else
**#d[count ] = push!(d[count],str[i]) , her i need to do some thing (append,push)..**
end
end
println(values(d))
end
str = ["eat", "tea", "tan", "ate", "nat", "bat"]
println(groupAnagrams(str))
and the output should be like that
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
any help ?
I’m guessing the line that goes here is:
push!(d[count], str[i])
and rather than d[count] = str[1], you wanted d[count] = [str[i]]
function groupAnagrams(str)
d = Dict{Int64,Array{String,1}}()
for i =1:length(str)
count = 0
for j=1:length(str[i])
count +=Int(str[i][j])
end
if !haskey(d,count)
d[count] = [str[i]]
#println(d)
else
push!(d[count], str[i])
end
end
#println(values(d))
for i in values(d)
println(i)
end
end
str = ["eat", "tea", "tan", "ate", "nat", "bat"]
println(groupAnagrams(str))
this work fine
thank you
Nice. You can also do:
function group_anagrams(strings)
d = Dict{Int64, Vector{String}}()
for str in strings
count = sum(Int, collect(str))
v = get!(d, count, Vector{String}[])
push!(v, str)
end
d
end
And if you don’t mind using a package:
julia> using SplitApplyCombine
julia> A = ["eat", "tea", "tan", "ate", "nat", "bat"]
6-element Array{String,1}:
"eat"
"tea"
"tan"
"ate"
"nat"
"bat"
julia> group(s -> String(sort(collect(s))), A)
3-element Dictionaries.Dictionary{String,Array{String,1}}
"aet" │ ["eat", "tea", "ate"]
"ant" │ ["tan", "nat"]
"abt" │ ["bat"]
This sorts each string and groups them together if the sorted string is the same, which happens if and only if two strings are anagrams of each other.
Much better method! I indeed forgot to note in my reply that both the original solution and mine don’t group only anagrams. See:
julia> group_anagrams(["eat", "dau"])
Dict{Int64,Array{String,1}} with 1 entry:
314 => ["eat", "dau"]
Edit:
Just wanted to mention this doesn’t necessarily require that package, only to change the calculation of the key:
function group_anagrams(strings)
d = Dict{String, Vector{String}}()
for str in strings
key = String(sort(collect(str)))
v = get!(d, key, Vector{String}[])
push!(v, str)
end
d
end
julia> group_anagrams(["eat", "dau"])
Dict{String,Array{String,1}} with 2 entries:
"aet" => ["eat"]
"adu" => ["dau"]