Author Topic: Map Routines  (Read 2108 times)

MrTAToad

  • Guest
Map Routines
« on: 2010-Oct-06 »
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
« Last Edit: 2010-Oct-06 by MrTAToad »

Offline bigsofty

  • Community Developer
  • Prof. Inline
  • ******
  • Posts: 2702
    • View Profile
Re: Map Routines
« Reply #1 on: 2010-Oct-06 »
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

  • Guest
Re: Map Routines
« Reply #2 on: 2010-Oct-06 »
I've mentioned that sort of thing to Gernot :)

Offline Kitty Hello

  • code monkey
  • Administrator
  • Prof. Inline
  • *******
  • Posts: 10762
  • here on my island the sea says 'hello'
    • View Profile
    • http://www.glbasic.com
Re: Map Routines
« Reply #3 on: 2010-Oct-12 »
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

  • Guest
Re: Map Routines
« Reply #4 on: 2010-Oct-12 »
Yes, C++ can be a pain :)

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