
The Dutch national flag is composed of three coloured bands in the order:

   red     (top)
   then white,   and
   lastly blue   (at the bottom). 


The problem posed by Edsger Dijkstra is:

Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...



Task
 Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag.
 Sort the balls in a way idiomatic to your language.
 Check the sorted balls are in the order of the Dutch national flag.


C.f.

 Dutch national flag problem
 Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)


      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!"