BBC BASIC for Windows
Programming >> BBC BASIC language >> Associative Arrays
http://bb4w.conforums.com/index.cgi?board=language&action=display&num=1384600561

Associative Arrays
Post by g3nrw on Nov 16th, 2013, 10:16am

I want to set up a string array CAT$(9999), with each element containing a two-character code followed by a free-text description. For example:
~~~~~~~~~~~~~~~~
CAT$(14)="EX 035 CW Clipping 4mS"
CAT$(15)="EX 035 CW Clipping 6mS"
CAT$(35)="MD Mode USB"
~~~~~~~~~~~~~~~~

Is there a quick BB4W way to find the free text for an element once the two-character code is known, without doing a (perhaps lengthy) search for a match from the start of the array?

I thought of setting up the entries in strict alphabetical order of 2-character code, then doing a binary chop, but is there a quicker way?

Ian




Re: Associative Arrays
Post by admin on Nov 16th, 2013, 1:09pm

on Nov 16th, 2013, 10:16am, g3nrw wrote:
I thought of setting up the entries in strict alphabetical order of 2-character code, then doing a binary chop, but is there a quicker way?

There's unlikely to be a quicker way, since SORTLIB is very fast (it's a machine-code shell sort) and the binary chop is very efficient. So if speed is your main concern that's the way I would recommend. Do remember to use the latest version of SORTLIB and specify ASCII sorting, so you can use regular comparison operators in the binary chop:

http://bb4w.wikispaces.com/Searching+ordered+lists

As far as alternative methods are concerned, you could prefix each element with a unique character and use INSTR:

Code:
      DIM CAT$(9999)
      CAT$() = "*"

      CAT$(14) = "*EX 035 CW Clipping 4mS"
      CAT$(15) = "*EX 035 CW Clipping 6mS"
      CAT$(35) = "*MD Mode USB"

      all$ = SUM(CAT$())
      REPEAT
        INPUT "Enter two-letter code: "code$
        I% = INSTR(all$, "*"+code$)
        IF I% THEN
          J% = INSTR(all$, "*", I%+1)
          PRINT "Free text is " MID$(all$, I%+4, J%-I%-4)
        ELSE
          PRINT "Not found"
        ENDIF
      UNTIL FALSE 

Of course you'd need to use BB4W version 6 if the total length of all the array elements exceeds 65535 characters.

Richard.
Re: Associative Arrays
Post by g3nrw on Nov 18th, 2013, 7:14pm

on Nov 16th, 2013, 1:09pm, Richard Russell wrote:
There's unlikely to be a quicker way,
[snip]
Richard.


Thanks Richard. Food for thought

Ian