Problem with looking for something in a ds list

Discussion in 'Programming' started by Ukaygee, Jun 17, 2018.

  1. Ukaygee

    Ukaygee Member

    Joined:
    Oct 28, 2017
    Posts:
    158
    Hi, so I'm looking for a specific value within a map.

    I tried ds_map_find_next, with the help of the manual, but that did not work.

    I know with lists, there is ds_list_find_index, but I'm wondering if there is this sort of function for a map?

    Anyone have any ideas?
     
  2. chamaeleon

    chamaeleon Member

    Joined:
    Jun 21, 2016
    Posts:
    1,076
    What did you do that is different from this (untested) code
    Code:
    var k = ds_map_find_first(mymap);
    while (!is_undefined(k) && mymap[? k] != myvalue)
    {
        k = ds_map_find_next(mymap, k);
    }
    if (!is_undefined(k))
    {
        ... Do something with k
    }
    
     
  3. PNelly

    PNelly Member

    Joined:
    Jun 20, 2016
    Posts:
    256
    What makes maps useful is that they eliminate the need for that kind of search, you can associate a value with a name, and then lookup that value by using the name when you need it.

    // your character picks up a sword
    ds_map_add(my_map, "sword_power", 100);

    // your character picks up a different sword
    ds_map_replace(my_map, "sword_power", 200);

    // your character hits an enemy
    damage = ds_map_find_value(my_map, "sword_power");

    If you need to perform an iterative search through your data then a list or array would be the way to go. The approach @chamaeleon suggests will work (as in, produce correct results), but it's very inefficient. I've seen it slow to a frame-busting crawl for map sizes of just a few hundred elements.
     
  4. chamaeleon

    chamaeleon Member

    Joined:
    Jun 21, 2016
    Posts:
    1,076
    What @Ukaygee is looking for is the equivalent of ds_list_find_index, which in theory could have been named ds_map_find_key.. Since it's not there, code along what I wrote is necessary, or you could use two maps, with the caveat that keys can only be strings or integers and use something like below.
    Code:
    my_key_map[? k] = v;
    my_value_map[? v] = k;
    
    And then look up in either map depending on the specific need, and any updates made to one map would have to be carefully managed
    Code:
    ds_map_delete(my_value_map, my_key_map[? k]);
    my_key_map[? k] = new_v;
    my_value_map[? new_v] = k;
    
     
  5. Ukaygee

    Ukaygee Member

    Joined:
    Oct 28, 2017
    Posts:
    158

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice