Map Routines

Previous topic - Next topic

MrTAToad

The included file is a routine for mapping Key/Value pairs.  As suggested by Gernot, I modified part of the ddgui_index function to search for text, and whilst may be slightly slower than a binary tree search, it should offer little noticeable performance loss.

The idea of this routine is to allow quick access for a value of a key, and is used by by Localisation routine.

Code (glbasic) Select

TYPE tKeyValue
key$
value$
ENDTYPE

TYPE TMap
list[] AS tKeyValue

FUNCTION Initialise%:
DIM self.list[0]
RETURN TRUE
ENDFUNCTION

FUNCTION Add%:key$,value$
LOCAL temp AS tKeyValue

IF self.search(key$)<0
// Found
temp.key$=key$
temp.value$=value$
DIMPUSH self.list[],temp
SORTARRAY self.list[],0
RETURN TRUE
ENDIF

RETURN FALSE
ENDFUNCTION

FUNCTION search%:key$
LOCAL up%,down%,mid%

up%=0
down%=BOUNDS(self.list[],0)-1
WHILE up%<down%
mid%=(up%+down%)/2
IF self.list[mid%].key$>key$
down%=MAX(mid%-1,up%)
ELSEIF self.list[mid%].key$<key$
up%=MIN(down%,mid%+1)
ELSE
RETURN mid% // Found
ENDIF
WEND

IF BOUNDS(self.list[],0)>0 AND self.list[up%].key$=key$
RETURN up%
ELSE
RETURN -1
ENDIF
ENDFUNCTION

FUNCTION GetValue$:key$,notFound$="NOT_FOUND"
LOCAL index%

index%=self.search(key$)
IF index%>=0
RETURN self.list[index%].value$
ELSE
RETURN notFound$
ENDIF
ENDFUNCTION

FUNCTION DeleteKey%:key$
LOCAL index%

index%=self.search(key$)
IF index%>=0
DIMDEL self.list[],index%
RETURN TRUE
ELSE
RETURN FALSE
ENDIF
ENDFUNCTION

FUNCTION Count%:
RETURN BOUNDS(self.list[],0)
ENDFUNCTION
ENDTYPE

bigsofty

Handy, thank you!

On a side note, it would be great if different types could be placed onto the list but I don't think that's possible yet with the new type system.

Cheers,


Ian
Cheers,

Ian.

"It is practically impossible to teach good programming style to students that have had prior exposure to BASIC.  As potential programmers, they are mentally mutilated beyond hope of regeneration."
(E. W. Dijkstra)

MrTAToad

I've mentioned that sort of thing to Gernot :)

Kitty Hello

you'd need a base class and such then. That what everyone and his dog complains about in C++, that it's so complicated.

MrTAToad

Yes, C++ can be a pain :)

I just keep to the simple things... =D