The select method in Ruby is simple and straight forward. It will select elements in an array matching a specific criteria.
For example,
>> x = [4,5,7,89,4,5,3,6,8,9,4,45,56,23,2,7,3,5,4,224,234,565,546,345,23,234,234,234,23466,25,54]
x = [4,5,7,89,4,5,3,6,8,9,4,45,56,23,2,7,3,5,4,224,234,565,546,345,23,234,234,234,23466,25,54]
=> [4, 5, 7, 89, 4, 5, 3, 6, 8, 9, 4, 45, 56, 23, 2, 7, 3, 5, 4, 224, 234, 565, 546, 345, 23, 234, 234, 234, 23466, 25, 54]
>> y = x.select{|m| m>20 && m<200}
y = x.select{|m| m>20 && m<200}
=> [89, 45, 56, 23, 23, 25, 54]
One problem about this is obviously is the time penalty. Select has to go through all the values in that array and does a sequential check which would result this run in O(n) time. Is there a better alternative to select which does it in a lesser time. Space is not an issue for me.
I am talking on cases where the same select is being used repetitively. If I am going to use the same select conditions 1000 times in a loop for an array of size n, then I will have to do the operation like 1000 * n times. Whereas if its optimized for space, I would only be doing 1000 * 1 times.
Thanks.
I’m not aware of a way to perform an operation on every element in an array in better than linear time — the idea sounds self-contradictory. You could memoize the result if you need to do the same calculation on the same array more than once to trade space for constant-time performance on subsequent runs, but I think O(n) is as good as it gets otherwise.