RosettaCodeData/Task/Dutch-national-flag-problem/BBC-BASIC/dutch-national-flag-problem.basic
2023-07-01 13:44:08 -04:00

38 lines
1.2 KiB
Text

INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
nBalls% = 12
DIM Balls$(nBalls%-1), Weight%(nBalls%-1), DutchFlag$(2)
DutchFlag$() = "Red ", "White ", "Blue "
REM. Generate random list of balls, ensuring not sorted:
REPEAT
prev% = 0 : sorted% = TRUE
FOR ball% = 0 TO nBalls%-1
index% = RND(3) - 1
Balls$(ball%) = DutchFlag$(index%)
IF index% < prev% THEN sorted% = FALSE
prev% = index%
NEXT
UNTIL NOT sorted%
PRINT "Random list: " SUM(Balls$())
REM. Assign Dutch Flag weightings to ball colours:
DutchFlag$ = SUM(DutchFlag$())
FOR ball% = 0 TO nBalls%-1
Weight%(ball%) = INSTR(DutchFlag$, Balls$(ball%))
NEXT
REM. Sort into Dutch Flag colour sequence:
C% = nBalls%
CALL Sort%, Weight%(0), Balls$(0)
PRINT "Sorted list: " SUM(Balls$())
REM Final check:
prev% = 0 : sorted% = TRUE
FOR ball% = 0 TO nBalls%-1
weight% = INSTR(DutchFlag$, Balls$(ball%))
IF weight% < prev% THEN sorted% = FALSE
prev% = weight%
NEXT
IF NOT sorted% PRINT "Error: Balls are not in correct order!"