- Home /
How can I get all array/list values within a given range?
Given a sorted array/list/hashtable/dictionary/sortedlist/etc of values, what would be the best way to derive a selection of all the values between two values?
var currentTime = 10;
var allTimes = [1,2,4,7,8,9,11,14,16,17,17,19,22,28,46];
// Returns a new list with [11,14,16,17,17,19]
var nextFewTimes = GetListWithinRange(allTimes, currentTime, currentTime+10);
Answer by whydoidoit · Feb 14, 2014 at 05:47 AM
Given a sorted list or array use BinarySearch to get the lowest and highest values.
The two searches will be O(logN), presuming you can leave the data in situ then there would be no need to read the individual values until processing was required.
Answer by MakeCodeNow · Feb 14, 2014 at 01:25 AM
The answer depends on what kind of container you are using, but if it's a simple linear container like a list or array, then just use a for loop. It's linear time (O(N)), which is totally fine unless this array is really enormous and GetListWithinRange is run a lot.
This is actually meant to read ti$$anonymous$$g data for a rhythm game (floats ins$$anonymous$$d of ints), so the list will be fairly large and GetListWithinRange will be called every update...
A friend just gave me the idea to use binary searches to find the positions of the $$anonymous$$ and max values within the time window, then copy everything between those to a new list. That sounds like it'd probably be faster.
And now that I think about it, I really only need to call GetListWithinRange at the beginning. After that, it simply needs to check the lowest-valued items in the original and derived lists -- which should be the first items in each list -- to see if they're within the time window and shift them accordingly.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
how can I get values stored in a list? 3 Answers
Find the correct index number for array inside two loops 2 Answers
Argument Out of Range On a List 2 Answers