Finding which variable name contains the lowest value
John Kauffman
Posts: 653
in BASIC Stamp
I have no problem for multiple variables finding the lowest value (lots of algorithms on StackOverflow).
But I need to display the variable *name* that is holding the lowest. Any suggestions for something better than below?
' ??? for 4 variables named: A, B, C, D containing byte values
' Is below best way to display name of var holding lowest value ?????
IF (A<B) AND (A<C) AND (A<D) THEN
DEBUG "A smallest"
ELSEIF (B<C) AND (B<D) THEN
DEBUG "B smallest"
ELSEIF C<D THEN
DEBUG "C smallest"
ELSE
DEBUG "D smallest"
ENDIF
But I need to display the variable *name* that is holding the lowest. Any suggestions for something better than below?
' ??? for 4 variables named: A, B, C, D containing byte values
' Is below best way to display name of var holding lowest value ?????
IF (A<B) AND (A<C) AND (A<D) THEN
DEBUG "A smallest"
ELSEIF (B<C) AND (B<D) THEN
DEBUG "B smallest"
ELSEIF C<D THEN
DEBUG "C smallest"
ELSE
DEBUG "D smallest"
ENDIF

Comments
You could also replace each of the DEBUG statements with a line that sets a byte variable to "A", "B", "C", or "D" and then put `DEBUG char, " smallest"` after the ENDIF:
I suspect the first might be both faster and smaller, but I really don't know, so try both if it matters. The second one has the advantage that it leaves the result in char, in case you need it later.
There's not much else you can do, since variable names don't make it into the tokenized binary that gets sent to the Stamp.
Another possibility is that the names will actually be strings. Here is a way to manage that.
nameloc VAR WORD A VAR BYTE B VAR BYTE C VAR BYTE D VAR BYTE char VAR BYTE smallest VAR BYTE idx VAR NIB main: DO ' ... ' gosub findname LOOP findName: smallest = A MAX B MAX C MAX D ' strangely enough, finds the minimum value LOOKDOWN smallest,[A,B,C,D],idx ' the index of the minimum value LOOKUP idx,[aname,bname,cname,dname],nameloc ' nameloc points to the name GOSUB showname RETURN showname: DEBUG "name is " idx=0 DO READ nameloc+idx,char IF char=0 THEN EXIT DEBUG char idx=idx+1 LOOP DEBUG CR RETURN aname DATA "Peter",0 bname DATA "Paul",0 cname DATA "Mary",0 dname DATA "Rumpelstiltskin",0