AlliedModders

AlliedModders (https://forums.alliedmods.net/index.php)
-   Scripting Help (https://forums.alliedmods.net/forumdisplay.php?f=11)
-   -   Array module and iterating through a map (https://forums.alliedmods.net/showthread.php?t=25872)

akysiev 03-22-2006 11:17

Array module and iterating through a map
 
Hi there. I've been scripting for a while and have only recently run into this problem with the array module. I've looked around but haven't been able to find any information on how to properly iterate through a map (keytable/hashtable).

I use the following for lists:
Code:
new iKey = list_first(list, 0); for(new i = iKey; i < list_size(list); i++) {     if(list_isfilled(list, iKey))     {         // do whatever     }     iKey = list_next(list, iKey); }

Everything runs fine using this but when it comes to keytables, there is no size() method (clearly) so I cannot do that. I've tried the following code and variations of it but no luck so far. Simply put, it either never enters the loop or runs it infinitely and obviously not executing logic as I intended it to.

Code:
new szKey[512]; map_first(table, "", szKey, strlen(szKey)); while(map_isfilled(table, szKey)) {     // do whatever     map_next(table, szKey, szKey, strlen(szKey)); }

Have also tried it with the null character as the limiting key in map_first but no luck.

Is there any proper way to iterate through a keytable/hashtable? This is essential for my script and I'd really rather not code the entire thing without keytables.

Thanks in advance!

akysiev 03-22-2006 13:29

Okay after a bit of testing I've found that the problem with the loop is that it will successfully complete one pass through the entire keytable but will remain stuck on the last index. Basically, map_next() keeps returning the very last index even after that's already been done once, and thus generating an infinite loop.

Just in case anyone else is interested (doubt it), I've managed to solve the problem by modifying my loop to this:

Code:
new szKey[512]; new szLastKey[512]; map_first(table, "", szKey, strlen(szKey)); while(map_isfilled(table, szKey) && !equal(szLastKey, szKey)) {     // do whatever     copy(szLastKey, 511, szKey);     map_next(table, szKey, szKey, strlen(szKey)); }

Now unfortunately, this also causes a slower runtime. The original (failed) loop was O(n), which happens to be great. While the equal method here I assume is a bit-by-bit comparison - which shouldn't affect the overall performance too much - the copy method I'm not as certain about but I won't waste my time looking it up in the source code.

Still, if anyone has an alternative to this that changes it to pure O(n) efficiency, I'd be quite interested. Not that I'd be using the keytable to store more than a few thousand values, but until you hit the limit where you can't make it any faster... :wink:


All times are GMT -4. The time now is 16:36.

Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.