Jump to content
Sign in to follow this  
Prodavec

Fastest search in Collection

Recommended Posts

For example we have collection (array):

_collection = [ [2, 10], [5, 20], [8, 35], [9, 12] ];

We have to get 2th element from that collection by its internal value "8". The simpliest but not optimized way is:

_internalValue = 8;
_item = [];
{
   if (_internalValue == (_x select 0)) exitWith
   {
       _item = _x;
   };
} forEach _collection;

We will get [8, 35].

But there's a performance problem: we have to ennumerate all elements in collection manually instead of using find command. Find command can return index (or -1) of the found element but it can't search ing nested arrays. Find command works much-much more faster than scripted solution with forEach loop + if (). In my case I should get (or precache) all internal values to use find command:

_allInternalValues = [];
{
   _allInternalValues set [count _allInternalValues, _x select 0];
} forEach _collection;

Now we have the second array:

[2, 5, 8, 9]

and can use find command instead of forEach loop:

_index = _allInternalValues find _internalValue;
if (_index > -1) then
{
   _item = _collection select _index;
};

Even we have an array with 1 000 000 elements it will work very fast if we will use FIND with precached internal values at the first entering to the script. But there's a penalty: we must precache all values first, even we have to search one element in large collection.

Have someone suggestion or specific to arma algorythm to search in nested arrays as fast as it possible.

Share this post


Link to post
Share on other sites

Not sure if you want to search all values of your collection values or you are just after a keyed array type solution.

If your just wanting to do lookups on one of your values I suggest you look at Sanjo's excellent Dictionary implementation


_collection = call Dictionary_fnc_new;
[_collection, 0, [1, 2, 3]] call Dictionary_fnc_set;
[_collection, 1, [1, 2, 3]] call Dictionary_fnc_set;
[_collection, 2, [1, 2, 3]] call Dictionary_fnc_set;


_keyToFind = 2
if(_keyToFind in _collection select 0)
{
// found
_values = [_collection, _keyToFind] call Dictionary_fnc_get;
};

Share this post


Link to post
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
Sign in to follow this  

×