QB / QB64 Discussion Forum      Other Subforums, Links and Downloads
  << Previous Topic | Next Topic >>Return to Index  

What is the optimal 'toggle' effect ?

June 4 2011 at 8:49 AM
AlGoreIthm  (no login)


Situation: A light switch can either be ON or OFF.
If 'ON' = 1 and 'OFF' = 0, what is the optimal way to program a 'toggle' effect?

so: if I start with '0' and hit the spacebar, my '0' becomes '1'.
if I hit the spacebar again, my '1' goes back to being '0'. And so on.


The following is a working program that demonstrates the idea, but it's not optimal. The challenge is to optimize & simplify the program for the same output.

' ======================= ONLY an EXAMPLE not an ENTRY ============

counter% = 0
toggle% = 1

WHILE k$ <> CHR$(27)

k$ = INKEY$
IF k$ = CHR$(32) THEN
counter% = counter% + 1
IF counter% / 2 = counter% \ 2 THEN toggle% = 0 ELSE toggle% = 1
PRINT toggle%
END IF

WEND

 
 Respond to this message   
AuthorReply
lawgin
(no login)

counter% not needed

June 4 2011, 10:43 AM 

WHILE k$ <> CHR$(27)

IF INKEY$ = CHR$(32) THEN
toggle% = ABS(toggle% - 1)
PRINT toggle%
END IF

WEND

 
 Respond to this message   

(Login MCalkins)
Moderator

1 - toggle%

June 5 2011, 4:42 PM 

eliminates the ABS().

As ChronoKitsune showed, XOR is great for toggling specific individuals bits. If, instead, you want to toggle all the bits (for example: 0 to -1 to 0), you could use NOT.

Regards,
Michael

 
 Respond to this message   

(Login rpgfan3233)

XOR should work just fine.

June 4 2011, 12:05 PM 

toggle% = 1

WHILE k$ <> CHR$(27)
k$ = INKEY$
IF k$ = CHR$(32) THEN
toggle% = toggle% XOR 1
PRINT toggle%
END IF
WEND

 
 Respond to this message   
Current Topic - What is the optimal 'toggle' effect ?
  << Previous Topic | Next Topic >>Return to Index