Replying to:computablee
Do you use a hash table with buckets or another method to store/look up the elements?
I use INSTR
It's the fastest option in SB for small dictionaries.
Root / Submissions / [.]
DIM dictionary$[0] dictionary$=DICNEW() 'or DIM dictionary$[1](The first element stores the locations of all the values, so an "empty" dictionary array will have a length of 1.) Setting a value:
DICSET dictionary$,"key","value"Creates the key if it doesn't exist Getting a value:
value$=DICGET(dictionary$,"key")Returns "" if the key doesn't exist Loading a dictionary from DATA:
dictionary$=DICREAD(@LABEL) @LABEL DATA "key1","value1" DATA "key2","value2" DATA ""Checking if a key exists:
exists=DICCHECK(dictionary$,"key")Returns the location of the value (1 indexed) if the key exists, otherwise 0. Finding the number of keys in a dictionary:
size=DICSIZE(dictionary$)Get a list of keys:
DIM LIST$[0] LIST$=DICLIST(dictionary$)
'Replace \1 and \0 with CHR$(1) and CHR$(0) 'Add key: INC DIC$[0],CHR$(LEN(DIC$)+1)+"\1"+KEY$+"\0" PUSH DIC$,VAL$ 'Get value: DIC$[ASC(DIC$[0][INSTR(DIC$[0],"\1"+KEY$+"\0")-1])-1]
'Get a value. 'Returns "" if key doesn't exist. COMMON DEF DICGET(DIC$[],KEY$) VAR N%=INSTR(DIC$[0],"\1"+KEY$+"\0") IF N%!=-1 THEN RETURN DIC$[ASC(DIC$[0][N%-1])-1] ELSE RETURN "" ENDIF END 'Set a value. 'Adds key if it doesn't exist. COMMON DEF DICSET DIC$[],KEY$,VAL$ VAR N%=INSTR(DIC$[0],"\1"+KEY$+"\0") IF N%!=-1 THEN DIC$[ASC(DIC$[0][N%-1])-1]=VAL$ ELSE PUSH DIC$,VAL$ INC DIC$[0],CHR$(LEN(DIC$))+"\1"+KEY$+"\0" ENDIF END 'Setup/clear dictionary array. COMMON DEF DICNEW() DIM DIC$[1] RETURN DIC$ END 'Read DATA into a dictionary. '@LABEL 'DATA "KEY","VALUE",&,"" COMMON DEF DICREAD(LABEL$) RESTORE "0:"+LABEL$ DIM DIC$[1] READ KEY$ WHILE KEY$!="" READ VAL$ INC DIC$[0],CHR$(LEN(DIC$)+1)+"\1"+KEY$+"\0" PUSH DIC$,VAL$ READ KEY$ WEND RETURN DIC$ END 'Check if key exists. 'Returns position (1-indexed) or 0. COMMON DEF DICCHECK(DIC$[],KEY$) N%=INSTR(DIC$[0],"\1"+KEY$+"\0") IF N%==-1 THEN RETURN #FALSE RETURN ASC(DIC$[0][N%-1])-1 END 'Get the number of keys in a dictionary. COMMON DEF DICSIZE(DIC$[]) RETURN LEN(DIC$)-1 END 'Get a list of keys in a dictionary. COMMON DEF DICLIST(DIC$[]) DIM LIST$[0] VAR N%=-1 WHILE 1 VAR L%=N%+3 N%=INSTR(L%+1,DIC$[0],"\0") IF N%==-1 THEN RETURN LIST$ PUSH LIST$,MID$(DIC$[0],L%,N%-L%) WEND END