I’m trying to crate a data structure sort of like a dictionary in Python, but with ranged keys. Here’s the scenario:
I’m implementing a programming language for backwards compatibility with an old game. Each instruction in the game is put into a list, and a counter is incremented on every encounter of a newline character. The hope is that if the language has a run-time error, it will be able to look up what line the instruction was on in the table and display that back to the user.
So, if the error occurred on instruction 20, and line 3 contained instructions 15-30, then polling this structure for 20 should return 3.
Having a dictionary with an entry for every single instruction is possible, but also highly wasteful. Is there another way this can be done?
From your description, you have a monotonically increasing counter and a map function of the form (constants below just made up for example):
It seems as though a simple array (list, in Python) of transition points will suffice:
and then given x, you find the lowest value of i such that arr[i] >= x.
You can find that index with an interpolative search, which will be roughly O(log log n) where n is the length of the array (code left as an exercise 🙂 ).