Getting the last index of a map

Sandiman

Member
Is it possible to get the last index of a map when the value of the index is unknown?

For example, I would like to do something like this:
Code:
int[string] map;
map["a"] = 8;
map["b"] = 2;
map["c"] = 1;
map["x"] = 4;
map["y"] = 9;
map["z"] = 3;

string last = last_index_of(map);
print ( to_string(map[last]) );

In my make-believe world, the above code would print "3", and 'last' would have the value "z".

My initial thought is that this would be difficult in ASH due to typing constraints, but I figured I'd give it a shot. Does such a thing exist?
 

Sandiman

Member
Yeah, that's sort of what I'm trying to avoid. I have a 7-dimensional map with an undefined number of entries in each map. I'd rather not perform an O(n^7) operation. :)
 

Bale

Minion
[quote author=Sandiman link=topic=2135.msg10932#msg10932 date=1231196046]
Yeah, that's sort of what I'm trying to avoid. I have a 7-dimensional map with an undefined number of entries in each map. I'd rather not perform an O(n^7) operation. :)
[/quote]

Just an idea, but you could have an index to your map where you add a new entry (numbered from 1 up) every time you add a new item to your map.

string [int] index;

Feel free to sort the index if necessary. Adding a single entry to an already sorted array requires minimal work. Then the last entry in your map would be:
map[ index[ count(index) ] ]

Yeah, it's a bit of a work-around, but it does save you the trouble of an O(n^7) operation.
 

zarqon

Well-known member
If the indices are from a traversable set with known ranges (integers, mafia data types that correspond to integers) you could work your way backwards, e.g.:

PHP:
item last;
for i from 4000 downto 1 {
  last = to_item(i);
  if map contains last break;
}

A bit faster than a foreach. Just about the only index that wouldn't work with is strings.
 
Top