How to find successor of a key in a map?

My map has key as an integer. I need to find the next greater key than the given key. If the given key is greatest, then return the smallest key.

You are searching for the smallest key that is greater than the current key k? The following might work, but is untested.

{init, _} = Enum.at(map, 0)
k2 = Enum.reduce({init, init}, fn {key, _}, {smallest, next} ->
  smallest = if key < smallest, do: key, else: smallest
  next = if key < next and key > k, do: key, else: next
  {smallest, next}
end)
|> (fun {smallest, next} -> if next < k, then: smallest, else: next).()

But beware of the fact that this is an expensive operation as it has to search the map everytime you ask for another key.

If you just want to make sure you iterate a given map in proper order sorting them before iterating might be the better way to go.

1 Like

You might want to use a different datastore than a hashmap. What about arrays or tensor? :sunglasses:

4 Likes

I also agree with others that map doesn’t seem like a good choice here. Maybe gb_trees might work better?

4 Likes

You’re right, I need something like this. Thanks!

1 Like