Last active
October 16, 2022 04:50
-
-
Save digital-carver/1579a6321b4305a02f32627b52363b85 to your computer and use it in GitHub Desktop.
Indices of each unique element in an array - threaded
This file contains 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
function unique_ids3(itr) | |
# create individual dictionaries for each thread, | |
# where keys have the type of itr's elements | |
d = [Dict{eltype(itr), Vector{Int}}() for _ in 1:Threads.nthreads()] | |
# iterate through itr, using automatic threading | |
# :static ensures that threadid() remains constant within an iteration | |
Threads.@threads :static for index in eachindex(itr) | |
id = Threads.threadid() | |
@inbounds val = itr[index] | |
# check if the dictionary | |
if haskey(d[id], val) | |
push!(d[id][val],index) | |
else | |
# add value of itr if its not in v yet | |
d[id][val] = [index] | |
end | |
end | |
# merge the dictionaries for the different threads, using append! to merge the values | |
# where the dictionaries have the same key | |
return mergewith(append!, d...) |> values |> collect | |
end | |
function unique_ids_serial(itr) | |
#create dictionnary where keys have type of whatever itr is | |
d = Dict{eltype(itr), Vector{Int}}() | |
#iterate through values in itr | |
for (index,val) in pairs(itr) | |
#check if the dictionary | |
if haskey(d, val) | |
push!(d[val],index) | |
else | |
#add value of itr if its not in v yet | |
d[val] = [index] | |
end | |
end | |
return collect(values(d)) | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment