Maps and sort, aka my brain hurts

dj_d

Member
So I want to declare something like this:
Code:
float [int][item]stuff;
The idea is that the [int] is an index (for sorting), so it is unique.
There will only be one entry per item, so the [item] field is unique too.
The float is a quantity that I will be sorting by.

Assume there are a bunch of entries in "stuff" already where the float is 0. Now I want to iterate over each item in "stuff" and set the float based on which item it is. Like:
Code:
foreach x in stuff
  stuff[x] = somefunction(x);
This would work (I think) but for the [int] index. (note that later in the code I'd do something like "sort stuff by value"). So what's the right way to accomplish this?
 
Last edited:

jasonharper

Developer
With only one index variable specified in your foreach loop, it's going to receive the int keys, not the item keys. somefunction() will be called with an int, not an item, which doesn't seem like what you're looking for. Furthermore, to be able to assign the return value to stuff[x], somefunction() would have to return a value of type float[item], not just a float. Assuming that you actually want to declare that function as float somefunction(item), try this:
Code:
foreach intKey, itemKey in stuff
    stuff[intKey][itemKey] = somefunction(itemKey);

However, that still wouldn't enable you to use "sort stuff by value"! 'sort' only works with one dimension of a multidimensional map; sorting on the outer dimension (the int key) means that the 'value' of each entry will be of type float[item]. Maps aren't comparable in ASH, so this would leave the order of entries unchanged - it's certainly not going to look inside each of these sub-maps to compare the float value. The easiest way to make this work would be to have a one-dimensional map, with values that are a record containing the item and its corresponding float value.

If you absolutely must sort the map in its current form, you'd need a more complicated sort expression that looks inside the sub-maps. That can't be written as part of the 'sort' statement, but you could use a helper function:
Code:
float extractFirstValue(float[int] entry) {
    foreach intKey, floatValue in entry
        return floatValue;
}

sort stuff by extractFirstValue(value);
 

dj_d

Member
Hallelujah! It is illuminated. I'm particularly stoked about duel foreach iterators - got to put that in the wiki (I just added a section on foreach).

Is
Code:
foreach x,y in map
the same as
Code:
foreach x in map
{
  foreach y in map[x]
}
 
Code:
foreach x,y in map

y in that case is the value right? Implemented in r7514.

Rev 7514 - jasonharper (2 file(s) modified)
ASH foreach loops can now contain one more variable in the list than the
target map has indices; the additional variable, if present, gets assigned
the current value from the map (saving you the trouble of explicitly looking
it up inside the loop).
 
Last edited:
Top