Search code examples
hashmaprangejulia

Is there a julia structure allowing to search for a range of keys?


I know that I can use integer keys for a hashmap like the following example for a Dictionary. But Dictionaries are unordered and do not benefit from having integer keys.

julia> hashmap = Dict( 5 => "five", 9 => "nine", 16 => "sixteen", 70 => "seventy")
Dict{Int64,String} with 4 entries:
  9  => "nine"
  16 => "sixteen"
  70 => "seventy"
  5  => "five"

julia> hashmap[9]
"nine"

julia> hashmap[8:50] # I would like to be able to do this to get keys between 8 and 50 (9 and 16 here)
ERROR: KeyError: key 8:50 not found
Stacktrace:
 [1] getindex(::Dict{Int64,String}, ::UnitRange{Int64}) at ./dict.jl:477
 [2] top-level scope at REPL[3]:1

I'm looking for an ordered structure allowing access all it's keys within a certain range while benefiting from performance optimization due to sorted keys.


Solution

  • There is a dedicated library named DataStructures which has a SortedDict structure and corresponding search functions:

    using DataStructures
    d = SortedDict(5 => "five", 9 => "nine", 16 => "sixteen", 70 => "seventy")
    
    st1 = searchsortedfirst(d, 8)   # index of the first key greater than or equal to 8
    st2 = searchsortedlast(d, 50)  # index of the last key less than or equal to 50
    

    And now:

    julia> [(k for (k,v) in inclusive(d,st1,st2))...]
    3-element Array{Int64,1}:
      9
     16