Dutch national flag problem: Difference between revisions

Content added Content deleted
(Added uBasic/4tH version)
m (syntax highlighting fixup automation)
Line 27: Line 27:
{{trans|Python: Construct from ball counts}}
{{trans|Python: Construct from ball counts}}


<lang 11l>V colours_in_order = ‘Red White Blue’.split(‘ ’)
<syntaxhighlight lang="11l">V colours_in_order = ‘Red White Blue’.split(‘ ’)


F dutch_flag_sort3(items)
F dutch_flag_sort3(items)
Line 38: Line 38:
print(‘Original Ball order: ’balls)
print(‘Original Ball order: ’balls)
V sorted_balls = dutch_flag_sort3(balls)
V sorted_balls = dutch_flag_sort3(balls)
print(‘Sorted Ball Order: ’sorted_balls)</lang>
print(‘Sorted Ball Order: ’sorted_balls)</syntaxhighlight>


{{out}}
{{out}}
Line 49: Line 49:
This works for ABAP Version 7.40 and above, the color blue is excluded as an option for the last entry to insure an unsorted sequence.
This works for ABAP Version 7.40 and above, the color blue is excluded as an option for the last entry to insure an unsorted sequence.


<syntaxhighlight lang="abap">
<lang ABAP>
report z_dutch_national_flag_problem.
report z_dutch_national_flag_problem.


Line 208: Line 208:


write:|{ sequence }, is sorted? -> { dutch_national_flag_problem->is_sorted( sequence ) }|, /.
write:|{ sequence }, is sorted? -> { dutch_national_flag_problem->is_sorted( sequence ) }|, /.
</syntaxhighlight>
</lang>


{{output}}
{{output}}
Line 219: Line 219:
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit


PROC PrintArray(BYTE ARRAY a BYTE len)
PROC PrintArray(BYTE ARRAY a BYTE len)
Line 276: Line 276:
PrintE("Sorting is invalid!")
PrintE("Sorting is invalid!")
FI
FI
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Dutch_national_flag_problem.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Dutch_national_flag_problem.png Screenshot from Atari 8-bit computer]
Line 291: Line 291:
=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>with Ada.Text_IO, Ada.Numerics.Discrete_Random, Ada.Command_Line;
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Numerics.Discrete_Random, Ada.Command_Line;


procedure Dutch_National_Flag is
procedure Dutch_National_Flag is
Line 389: Line 389:


Print("After Sorting: ", A);
Print("After Sorting: ", A);
end Dutch_National_Flag;</lang>
end Dutch_National_Flag;</syntaxhighlight>


{{out}}
{{out}}
Line 404: Line 404:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>BEGIN # Dutch national flag problem: sort a set of randomly arranged red, white and blue balls into order #
<syntaxhighlight lang="algol68">BEGIN # Dutch national flag problem: sort a set of randomly arranged red, white and blue balls into order #
# ball sets are represented by STRING items, red by "R", white by "W" and blue by "B" #
# ball sets are represented by STRING items, red by "R", white by "W" and blue by "B" #
# returns the balls sorted into red, white and blue order #
# returns the balls sorted into red, white and blue order #
Line 480: Line 480:
print( ( "after: ", balls, IF sorted balls( balls ) THEN "" ELSE " NOT" FI, " sorted", newline ) )
print( ( "after: ", balls, IF sorted balls( balls ) THEN "" ELSE " NOT" FI, " sorted", newline ) )
OD
OD
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 493: Line 493:
=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang applescript>use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later — for these 'use' commands!
<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later — for these 'use' commands!
-- This script uses a customisable AppleScript sort available at <https://macscripter.net/viewtopic.php?pid=194430#p194430>.
-- This script uses a customisable AppleScript sort available at <https://macscripter.net/viewtopic.php?pid=194430#p194430>.
-- It's assumed that scripters will know how and where to install it as a library.
-- It's assumed that scripters will know how and where to install it as a library.
Line 526: Line 526:
end DutchNationalFlagProblem
end DutchNationalFlagProblem


DutchNationalFlagProblem(100)</lang>
DutchNationalFlagProblem(100)</syntaxhighlight>


{{output}}
{{output}}
Line 537: Line 537:
=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
{{trans|ZX_Spectrum_Basic}}
{{trans|ZX_Spectrum_Basic}}
<lang ApplesoftBasic> 100 READ C$(0),C$(1),C$(2)
<syntaxhighlight lang="applesoftbasic"> 100 READ C$(0),C$(1),C$(2)
110 DATARED,WHITE,BLUE,0
110 DATARED,WHITE,BLUE,0
120 PRINT "RANDOM:
120 PRINT "RANDOM:
Line 554: Line 554:
250 PRINT SPC( S)C$(B%(N));
250 PRINT SPC( S)C$(B%(N));
260 LET S = 1
260 LET S = 1
270 RETURN </lang>
270 RETURN </syntaxhighlight>
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotKey>RandGen(MaxBalls){
<syntaxhighlight lang="autohotkey">RandGen(MaxBalls){
Random,k,3,MaxBalls
Random,k,3,MaxBalls
Loop,% k{
Loop,% k{
Line 569: Line 569:
F:=RTrim(F,",")
F:=RTrim(F,",")
Sort,F,N D`,
Sort,F,N D`,
MsgBox,% F:=RegExReplace(RegExReplace(RegExReplace(F,"(1)","Red"),"(2)","White"),"(3)","Blue")</lang>
MsgBox,% F:=RegExReplace(RegExReplace(RegExReplace(F,"(1)","Red"),"(2)","White"),"(3)","Blue")</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
Given each color a value in descending order ( Red = 1, White = 2 And Blue = 3)
Given each color a value in descending order ( Red = 1, White = 2 And Blue = 3)
<syntaxhighlight lang="autoit">
<lang Autoit>
#include <Array.au3>
#include <Array.au3>
Dutch_Flag(50)
Dutch_Flag(50)
Line 598: Line 598:
_ArrayDisplay($avArray)
_ArrayDisplay($avArray)
EndFunc ;==>Dutch_Flag
EndFunc ;==>Dutch_Flag
</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
{{works with|gawk}}
{{works with|gawk}}
<lang awk>
<syntaxhighlight lang="awk">
BEGIN {
BEGIN {
weight[1] = "red"; weight[2] = "white"; weight[3] = "blue";
weight[1] = "red"; weight[2] = "white"; weight[3] = "blue";
Line 650: Line 650:
return 1
return 1
}
}
</syntaxhighlight>
</lang>


Output:
Output:


<lang>
<syntaxhighlight lang="text">
BEFORE: blue red white red white blue red white blue white
BEFORE: blue red white red white blue red white blue white


Line 660: Line 660:


Sorting is valid.
Sorting is valid.
</syntaxhighlight>
</lang>


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang qbasic>DECLARE color$[] = { "red", "white", "blue" }
<syntaxhighlight lang="qbasic">DECLARE color$[] = { "red", "white", "blue" }


DOTIMES 16
DOTIMES 16
Line 671: Line 671:
PRINT "Unsorted: ", ball$
PRINT "Unsorted: ", ball$


PRINT " Sorted: ", REPLACE$(SORT$(REPLACE$(ball$, "blue", "z")), "z", "blue")</lang>
PRINT " Sorted: ", REPLACE$(SORT$(REPLACE$(ball$, "blue", "z")), "z", "blue")</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 679: Line 679:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<lang BASIC256>arraybase 1
<syntaxhighlight lang="basic256">arraybase 1
dim flag = {"Red","White","Blue"}
dim flag = {"Red","White","Blue"}
dim balls(9)
dim balls(9)
Line 697: Line 697:
if balls[j] = kolor then print balls[j]; " |";
if balls[j] = kolor then print balls[j]; " |";
next j
next j
next i</lang>
next i</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> INSTALL @lib$+"SORTLIB"
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
Sort% = FN_sortinit(0,0)
Line 738: Line 738:
prev% = weight%
prev% = weight%
NEXT
NEXT
IF NOT sorted% PRINT "Error: Balls are not in correct order!"</lang>
IF NOT sorted% PRINT "Error: Balls are not in correct order!"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 746: Line 746:


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h> //printf()
<syntaxhighlight lang="c">#include <stdio.h> //printf()
#include <stdlib.h> //srand(), rand(), RAND_MAX, qsort()
#include <stdlib.h> //srand(), rand(), RAND_MAX, qsort()
#include <stdbool.h> //true, false
#include <stdbool.h> //true, false
Line 799: Line 799:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Accidentally still sorted:rrrww
<pre>Accidentally still sorted:rrrww
Line 806: Line 806:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iostream>


Line 846: Line 846:
dnf_partition(balls, balls + 9, WHITE, BLUE);
dnf_partition(balls, balls + 9, WHITE, BLUE);
print(balls, 9);
print(balls, 9);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 856: Line 856:


=={{header|C_sharp|C#}}==
=={{header|C_sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 931: Line 931:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Ceylon}}==
=={{header|Ceylon}}==
Be sure to add ceylon.random in your module.ceylon file.
Be sure to add ceylon.random in your module.ceylon file.
<lang ceylon>import ceylon.random {
<syntaxhighlight lang="ceylon">import ceylon.random {


DefaultRandom
DefaultRandom
Line 1,016: Line 1,016:
print(sortedBalls1);
print(sortedBalls1);
print(sortedBalls2);
print(sortedBalls2);
}</lang>
}</syntaxhighlight>




=={{header|Clojure}}==
=={{header|Clojure}}==
<lang Clojure>(defn dutch-flag-order [color]
<syntaxhighlight lang="clojure">(defn dutch-flag-order [color]
(get {:red 1 :white 2 :blue 3} color))
(get {:red 1 :white 2 :blue 3} color))


Line 1,038: Line 1,038:
(if in-dutch-flag-order?
(if in-dutch-flag-order?
(recur num-balls)
(recur num-balls)
balls)))</lang>
balls)))</syntaxhighlight>


{{out}}
{{out}}
Line 1,051: Line 1,051:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.random, std.algorithm, std.traits, std.array;
<syntaxhighlight lang="d">import std.stdio, std.random, std.algorithm, std.traits, std.array;


enum DutchColors { red, white, blue }
enum DutchColors { red, white, blue }
Line 1,081: Line 1,081:
writeln("\nSorted Ball Order:\n", balls);
writeln("\nSorted Ball Order:\n", balls);
assert(balls[].isSorted, "Balls not sorted.");
assert(balls[].isSorted, "Balls not sorted.");
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Original Ball order:
<pre>Original Ball order:
Line 1,090: Line 1,090:


===Bidirectional Range Version===
===Bidirectional Range Version===
<lang d>import std.stdio, std.random, std.algorithm, std.range,
<syntaxhighlight lang="d">import std.stdio, std.random, std.algorithm, std.range,
std.array, std.traits;
std.array, std.traits;


Line 1,161: Line 1,161:
assert(balls[0 .. n].isSorted());
assert(balls[0 .. n].isSorted());
}
}
}</lang>
}</syntaxhighlight>
The output is the same.
The output is the same.


Line 1,167: Line 1,167:
This version uses more contract programming and asserts to verify the code correctness.
This version uses more contract programming and asserts to verify the code correctness.
With hints from: toccata.lri.fr/gallery/flag.en.html
With hints from: toccata.lri.fr/gallery/flag.en.html
<lang d>import std.stdio, std.random, std.algorithm, std.traits, std.range;
<syntaxhighlight lang="d">import std.stdio, std.random, std.algorithm, std.traits, std.range;


enum Color : ubyte { blue, white, red }
enum Color : ubyte { blue, white, red }
Line 1,259: Line 1,259:
writeln("\nSorted Ball Order:\n", balls);
writeln("\nSorted Ball Order:\n", balls);
assert(balls[].isSorted, "Balls not sorted.");
assert(balls[].isSorted, "Balls not sorted.");
}</lang>
}</syntaxhighlight>
The output is the same.
The output is the same.


=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule Dutch_national_flag do
<syntaxhighlight lang="elixir">defmodule Dutch_national_flag do
defp ball(:red), do: 1
defp ball(:red), do: 1
defp ball(:white), do: 2
defp ball(:white), do: 2
Line 1,296: Line 1,296:
end
end


Dutch_national_flag.problem</lang>
Dutch_national_flag.problem</syntaxhighlight>


{{out}}
{{out}}
Line 1,307: Line 1,307:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>-module(dutch).
<syntaxhighlight lang="erlang">-module(dutch).
-export([random_balls/1, is_dutch/1, dutch/1]).
-export([random_balls/1, is_dutch/1, dutch/1]).


Line 1,332: Line 1,332:
dutch(R, W, B, [red | L]) -> dutch([red|R], W, B, L);
dutch(R, W, B, [red | L]) -> dutch([red|R], W, B, L);
dutch(R, W, B, [white | L]) -> dutch(R, [white|W], B, L);
dutch(R, W, B, [white | L]) -> dutch(R, [white|W], B, L);
dutch(R, W, B, [blue | L]) -> dutch(R, W, [blue|B], L).</lang>
dutch(R, W, B, [blue | L]) -> dutch(R, W, [blue|B], L).</syntaxhighlight>


Sample usage:
Sample usage:
<lang erlang>main(_) ->
<syntaxhighlight lang="erlang">main(_) ->
L = random_balls(10),
L = random_balls(10),
case is_dutch(L) of
case is_dutch(L) of
true -> io:format("The random sequence ~p is already in the order of the Dutch flag!~n", [L]);
true -> io:format("The random sequence ~p is already in the order of the Dutch flag!~n", [L]);
false -> io:format("The starting random sequence is ~p;~nThe ordered sequence is ~p.~n", [L, dutch(L)])
false -> io:format("The starting random sequence is ~p;~nThe ordered sequence is ~p.~n", [L, dutch(L)])
end.</lang>
end.</syntaxhighlight>


{{out}}
{{out}}
Line 1,349: Line 1,349:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>(* Since the task description here does not impose Dijsktra's original restrictions
<syntaxhighlight lang="fsharp">(* Since the task description here does not impose Dijsktra's original restrictions
* Changing the order is only allowed by swapping 2 elements
* Changing the order is only allowed by swapping 2 elements
* Every element must only be inspected once
* Every element must only be inspected once
Line 1,382: Line 1,382:
let sorted = rs @ ws @ bs
let sorted = rs @ ws @ bs
printfn "The sequence %A is sorted: %b" sorted (isDutch sorted)
printfn "The sequence %A is sorted: %b" sorted (isDutch sorted)
0</lang>
0</syntaxhighlight>
{{out}}
{{out}}
<pre>Sort the sequence of 10 balls: [Red; White; Red; Blue; White; White; Blue; Blue; White; White]
<pre>Sort the sequence of 10 balls: [Red; White; Red; Blue; White; White; Blue; Blue; White; White]
Line 1,389: Line 1,389:
=={{header|Factor}}==
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
{{works with|Factor|0.99 2020-01-23}}
<lang factor>USING: combinators grouping kernel math prettyprint random
<syntaxhighlight lang="factor">USING: combinators grouping kernel math prettyprint random
sequences ;
sequences ;


Line 1,408: Line 1,408:
] while 3nip ;
] while 3nip ;


10 3 random-non-sorted-integers dup . dnf-sort! .</lang>
10 3 random-non-sorted-integers dup . dnf-sort! .</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,423: Line 1,423:
https://github.com/bfox9900/CAMEL99-V2/blob/master/Video/DIJKSTRAFLAG%20.mp4
https://github.com/bfox9900/CAMEL99-V2/blob/master/Video/DIJKSTRAFLAG%20.mp4


<lang>\ Dutch flag DEMO for CAMEL99 Forth
<syntaxhighlight lang="text">\ Dutch flag DEMO for CAMEL99 Forth
\ *SORTS IN PLACE FROM Video MEMORY*
\ *SORTS IN PLACE FROM Video MEMORY*


Line 1,571: Line 1,571:
CR ." Completed"
CR ." Completed"
;
;
</syntaxhighlight>
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 1,577: Line 1,577:


Abhor code duplication. I've repeated code anyway to demonstrate FORTRAN pointers, which behave like an alias. A subroutine with traditional arguments including the number of valid elements of the array is appropriate. I'd use one long array instead of 3 arrays and the size intrinsic.
Abhor code duplication. I've repeated code anyway to demonstrate FORTRAN pointers, which behave like an alias. A subroutine with traditional arguments including the number of valid elements of the array is appropriate. I'd use one long array instead of 3 arrays and the size intrinsic.
<lang>
<syntaxhighlight lang="text">
!-*- mode: compilation; default-directory: "/tmp/" -*-
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon Jun 3 11:18:24
!Compilation started at Mon Jun 3 11:18:24
Line 1,683: Line 1,683:


end program Netherlands
end program Netherlands
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>
<syntaxhighlight lang="freebasic">
' El problema planteado por Edsger Dijkstra es:
' El problema planteado por Edsger Dijkstra es:
' "Dado un número de bolas rojas, azules y blancas en orden aleatorio,
' "Dado un número de bolas rojas, azules y blancas en orden aleatorio,
Line 1,710: Line 1,710:
Next i
Next i
End
End
</syntaxhighlight>
</lang>


=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=e57a862aff12647fa80c84a595161cb9 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=e57a862aff12647fa80c84a595161cb9 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim Red As String = "0"
Dim Red As String = "0"
Dim White As String = "1"
Dim White As String = "1"
Line 1,739: Line 1,739:
Next
Next


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,747: Line 1,747:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,834: Line 1,834:
f.sort3()
f.sort3()
fmt.Println(f)
fmt.Println(f)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,851: Line 1,851:
The function "sort" works with anything that belongs to the Eq and Ord classes.
The function "sort" works with anything that belongs to the Eq and Ord classes.
The function "randomRIO" takes a range of two integers to give a random value within the range. We make Color an instance of Enum so that we can give Red, White and Blue as integers to randomRIO and convert the random number back to Red, White or Blue.
The function "randomRIO" takes a range of two integers to give a random value within the range. We make Color an instance of Enum so that we can give Red, White and Blue as integers to randomRIO and convert the random number back to Red, White or Blue.
<lang Haskell>import Data.List (sort)
<syntaxhighlight lang="haskell">import Data.List (sort)
import System.Random (randomRIO)
import System.Random (randomRIO)
import System.IO.Unsafe (unsafePerformIO)
import System.IO.Unsafe (unsafePerformIO)
Line 1,876: Line 1,876:
False -> do
False -> do
putStrLn $ "The starting random sequence is " ++ show a ++ "\n"
putStrLn $ "The starting random sequence is " ++ show a ++ "\n"
putStrLn $ "The ordered sequence is " ++ show (dutch a)</lang>
putStrLn $ "The ordered sequence is " ++ show (dutch a)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,887: Line 1,887:


To understand ''why'' Dijsktra was interested in the problem, here's an example showing difficiency of using generic sort:
To understand ''why'' Dijsktra was interested in the problem, here's an example showing difficiency of using generic sort:
<lang haskell>inorder n = and $ zipWith (<=) n (tail n) -- or use Data.List.Ordered
<syntaxhighlight lang="haskell">inorder n = and $ zipWith (<=) n (tail n) -- or use Data.List.Ordered


mk012 :: Int -> Int -> [Int] -- definitely unordered
mk012 :: Int -> Int -> [Int] -- definitely unordered
Line 1,907: Line 1,907:
-- print $ inorder $ dutch1 s -- O(n)
-- print $ inorder $ dutch1 s -- O(n)
print $ inorder $ dutch2 s -- O(n)
print $ inorder $ dutch2 s -- O(n)
where s = mk012 10000000 42</lang>
where s = mk012 10000000 42</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 1,919: Line 1,919:
force at least one of each color ball, change "?n-1" to "?n" in the 3rd line.
force at least one of each color ball, change "?n-1" to "?n" in the 3rd line.


<lang unicon>procedure main(a)
<syntaxhighlight lang="unicon">procedure main(a)
n := integer(!a) | 20
n := integer(!a) | 20
every (nr|nw|nb) := ?n-1
every (nr|nw|nb) := ?n-1
Line 1,940: Line 1,940:
every (s := "") ||:= (find(c := !cset(w),w),c)
every (s := "") ||:= (find(c := !cset(w),w),c)
return s
return s
end</lang>
end</syntaxhighlight>


A few sample runs:
A few sample runs:
Line 1,962: Line 1,962:
=={{header|J}}==
=={{header|J}}==
We shall define a routine to convert the values 0 1 2 to ball names:
We shall define a routine to convert the values 0 1 2 to ball names:
<lang J>i2b=: {&(;:'red white blue')</lang>
<syntaxhighlight lang="j">i2b=: {&(;:'red white blue')</syntaxhighlight>
and its inverse
and its inverse
<lang J>b2i=: i2b inv</lang>
<syntaxhighlight lang="j">b2i=: i2b inv</syntaxhighlight>
Next, we need a random assortment of balls:
Next, we need a random assortment of balls:
<lang J> BALLS=: i2b ?20#3
<syntaxhighlight lang="j"> BALLS=: i2b ?20#3
BALLS
BALLS
┌────┬───┬────┬───┬───┬─────┬─────┬─────┬────┬────┬─────┬────┬────┬───┬────┬───┬─────┬───┬────┬───┐
┌────┬───┬────┬───┬───┬─────┬─────┬─────┬────┬────┬─────┬────┬────┬───┬────┬───┬─────┬───┬────┬───┐
│blue│red│blue│red│red│white│white│white│blue│blue│white│blue│blue│red│blue│red│white│red│blue│red│
│blue│red│blue│red│red│white│white│white│blue│blue│white│blue│blue│red│blue│red│white│red│blue│red│
└────┴───┴────┴───┴───┴─────┴─────┴─────┴────┴────┴─────┴────┴────┴───┴────┴───┴─────┴───┴────┴───┘</lang>
└────┴───┴────┴───┴───┴─────┴─────┴─────┴────┴────┴─────┴────┴────┴───┴────┴───┴─────┴───┴────┴───┘</syntaxhighlight>
And we want to sort them in their canonical order:
And we want to sort them in their canonical order:
<lang J> /:~&.b2i BALLS
<syntaxhighlight lang="j"> /:~&.b2i BALLS
┌───┬───┬───┬───┬───┬───┬───┬─────┬─────┬─────┬─────┬─────┬────┬────┬────┬────┬────┬────┬────┬────┐
┌───┬───┬───┬───┬───┬───┬───┬─────┬─────┬─────┬─────┬─────┬────┬────┬────┬────┬────┬────┬────┬────┐
│red│red│red│red│red│red│red│white│white│white│white│white│blue│blue│blue│blue│blue│blue│blue│blue│
│red│red│red│red│red│red│red│white│white│white│white│white│blue│blue│blue│blue│blue│blue│blue│blue│
└───┴───┴───┴───┴───┴───┴───┴─────┴─────┴─────┴─────┴─────┴────┴────┴────┴────┴────┴────┴────┴────┘</lang>
└───┴───┴───┴───┴───┴───┴───┴─────┴─────┴─────┴─────┴─────┴────┴────┴────┴────┴────┴────┴────┴────┘</syntaxhighlight>
Note that if we were not using J's built in sort, we would probably want to use [[Counting_sort|bin sort]] here.
Note that if we were not using J's built in sort, we would probably want to use [[Counting_sort|bin sort]] here.


Anyways, we can test that they are indeed sorted properly:
Anyways, we can test that they are indeed sorted properly:
<lang J> assert@(-: /:~)&b2i /:~&.b2i BALLS</lang>
<syntaxhighlight lang="j"> assert@(-: /:~)&b2i /:~&.b2i BALLS</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
The elements of an <code>enum</code> implement <code>Comparable</code> so the build-in sort works. You can also use this comparability to check the sort has worked.
The elements of an <code>enum</code> implement <code>Comparable</code> so the build-in sort works. You can also use this comparability to check the sort has worked.
<lang java>import java.util.Arrays;
<syntaxhighlight lang="java">import java.util.Arrays;
import java.util.Random;
import java.util.Random;


Line 2,012: Line 2,012:
System.out.println("Correctly sorted: " + sorted);
System.out.println("Correctly sorted: " + sorted);
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,021: Line 2,021:
=={{header|Javascript}}==
=={{header|Javascript}}==
===ES6===
===ES6===
<lang javascript>const dutchNationalFlag = () => {
<syntaxhighlight lang="javascript">const dutchNationalFlag = () => {


/**
/**
Line 2,102: Line 2,102:
};
};
dutchNationalFlag();
dutchNationalFlag();
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,117: Line 2,117:


'''Function'''
'''Function'''
<syntaxhighlight lang="julia">
<lang Julia>
const COLORS = ["red", "white", "blue"]
const COLORS = ["red", "white", "blue"]


Line 2,142: Line 2,142:
dutchsort!(copy(a), lo, hi)
dutchsort!(copy(a), lo, hi)
end
end
</syntaxhighlight>
</lang>


'''Main'''
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
function formatdf(a::Array{ASCIIString,1})
function formatdf(a::Array{ASCIIString,1})
i = 0
i = 0
Line 2,176: Line 2,176:
@time e = sort(d, by=x->findfirst(COLORS, x))
@time e = sort(d, by=x->findfirst(COLORS, x))
println(formatdf(e))
println(formatdf(e))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,196: Line 2,196:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|D}}
{{trans|D}}
<lang scala>// version 1.1.4
<syntaxhighlight lang="scala">// version 1.1.4


import java.util.Random
import java.util.Random
Line 2,248: Line 2,248:
// print the colors of the balls after sorting
// print the colors of the balls after sorting
println("After sorting : ${balls.contentToString()}")
println("After sorting : ${balls.contentToString()}")
}</lang>
}</syntaxhighlight>


Sample output:
Sample output:
Line 2,257: Line 2,257:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define orderdutchflag(a) => {
<syntaxhighlight lang="lasso">define orderdutchflag(a) => {
local(r = array, w = array, b = array)
local(r = array, w = array, b = array)
with i in #a do => {
with i in #a do => {
Line 2,272: Line 2,272:
}
}


orderdutchflag(array('Red', 'Red', 'Blue', 'Blue', 'Blue', 'Red', 'Red', 'Red', 'White', 'Blue'))</lang>
orderdutchflag(array('Red', 'Red', 'Blue', 'Blue', 'Blue', 'Red', 'Red', 'Red', 'White', 'Blue'))</syntaxhighlight>
{{out}}
{{out}}
<pre>array(Red, Red, Red, Red, Red, White, Blue, Blue, Blue, Blue)</pre>
<pre>array(Red, Red, Red, Red, Red, White, Blue, Blue, Blue, Blue)</pre>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>; We'll just use words for the balls
<syntaxhighlight lang="logo">; We'll just use words for the balls
make "colors {red white blue}
make "colors {red white blue}


Line 2,344: Line 2,344:
setitem :a :array item :b :array
setitem :a :array item :b :array
setitem :b :array :temp
setitem :b :array :temp
end</lang>
end</syntaxhighlight>


Test code:
Test code:
<lang>do.while [
<syntaxhighlight lang="text">do.while [
make "list random_balls 10
make "list random_balls 10
] [dutch? :list]
] [dutch? :list]
Line 2,353: Line 2,353:
print (sentence [Start list:] arraytolist :list)
print (sentence [Start list:] arraytolist :list)
print (sentence [Sorted:] arraytolist dutch :list)
print (sentence [Sorted:] arraytolist dutch :list)
bye</lang>
bye</syntaxhighlight>


{{out}}
{{out}}
Line 2,361: Line 2,361:
=={{header|Lua}}==
=={{header|Lua}}==
The task seems to allow for some interpretation, so attempting to follow as literally as possible.
The task seems to allow for some interpretation, so attempting to follow as literally as possible.
<lang lua>-- "1. Generate a randomized order of balls.."
<syntaxhighlight lang="lua">-- "1. Generate a randomized order of balls.."
math.randomseed(os.time())
math.randomseed(os.time())
N, balls, colors = 10, {}, { "red", "white", "blue" }
N, balls, colors = 10, {}, { "red", "white", "blue" }
Line 2,387: Line 2,387:
-- "3. Check the sorted balls are in the order of the Dutch national flag."
-- "3. Check the sorted balls are in the order of the Dutch national flag."
print("SORTED: "..table.concat(balls,","))
print("SORTED: "..table.concat(balls,","))
print(issorted(balls) and "Properly sorted." or "IMPROPERLY SORTED!!")</lang>
print(issorted(balls) and "Properly sorted." or "IMPROPERLY SORTED!!")</syntaxhighlight>
{{out}}
{{out}}
<pre>RANDOM: white,white,blue,blue,red,red,blue,white,red,white
<pre>RANDOM: white,white,blue,blue,red,red,blue,white,red,white
Line 2,396: Line 2,396:
Most times the Three Way Partition makes more changed than the first algorithm. Also if the array is sorted from the start, no changes give the first algorithm and 23 changes the Three Way Partition,
Most times the Three Way Partition makes more changed than the first algorithm. Also if the array is sorted from the start, no changes give the first algorithm and 23 changes the Three Way Partition,


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Report "Dutch Flag from Dijkstra"
Report "Dutch Flag from Dijkstra"
const center=2
const center=2
Line 2,561: Line 2,561:
Print "changes: "; many
Print "changes: "; many


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,581: Line 2,581:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>flagSort[data_List] := Sort[data, (#1 === RED || #2 === BLUE) &]</lang>
<syntaxhighlight lang="mathematica">flagSort[data_List] := Sort[data, (#1 === RED || #2 === BLUE) &]</syntaxhighlight>
{{out}}
{{out}}
<pre>flagSort[{WHITE, RED, RED, WHITE, WHITE, BLUE, WHITE, BLUE, BLUE, WHITE, WHITE, BLUE}]
<pre>flagSort[{WHITE, RED, RED, WHITE, WHITE, BLUE, WHITE, BLUE, BLUE, WHITE, WHITE, BLUE}]
Line 2,592: Line 2,592:
The number of colors may be specified as argument in the command line. By default, 10 colors are randomly chosen.
The number of colors may be specified as argument in the command line. By default, 10 colors are randomly chosen.


<lang Nim>import os, random, strutils
<syntaxhighlight lang="nim">import os, random, strutils


type Color {.pure.} = enum Red = "R", White = "W", Blue = "B"
type Color {.pure.} = enum Red = "R", White = "W", Blue = "B"
Line 2,655: Line 2,655:
threeWayPartition(sortedColors, White)
threeWayPartition(sortedColors, White)
doAssert sortedColors.isSorted()
doAssert sortedColors.isSorted()
echo "Sorted: ", sortedColors.join("")</lang>
echo "Sorted: ", sortedColors.join("")</syntaxhighlight>


{{out}}
{{out}}
Line 2,664: Line 2,664:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
A [[counting sort]] might be more appropriate here, but that would conceal the details of the sort.
A [[counting sort]] might be more appropriate here, but that would conceal the details of the sort.
<lang parigp>compare(a,b)={
<syntaxhighlight lang="parigp">compare(a,b)={
if (a==b,
if (a==b,
0
0
Line 2,677: Line 2,677:
while(inorder(v), v=r(10));
while(inorder(v), v=r(10));
v=vecsort(v,compare);
v=vecsort(v,compare);
inorder(v)</lang>
inorder(v)</syntaxhighlight>


{{out}}
{{out}}
Line 2,684: Line 2,684:
=={{header|Perl}}==
=={{header|Perl}}==
The task is probably not to just sort an array. The wikipedia links has a slightly better explanation that leads to the following code:
The task is probably not to just sort an array. The wikipedia links has a slightly better explanation that leads to the following code:
<lang perl>use warnings;
<syntaxhighlight lang="perl">use warnings;
use strict;
use strict;
use 5.010; # //
use 5.010; # //
Line 2,755: Line 2,755:


show($balls);
show($balls);
are_ordered($balls) or die "Incorrect\n";</lang>
are_ordered($balls) or die "Incorrect\n";</syntaxhighlight>
You can run it with no parameters, it sorts 10 balls in such a case. If you provide one parameter, it is used as the number of balls. The second parameter turns on debugging that shows how the balls are being swapped.
You can run it with no parameters, it sorts 10 balls in such a case. If you provide one parameter, it is used as the number of balls. The second parameter turns on debugging that shows how the balls are being swapped.


=={{header|Phix}}==
=={{header|Phix}}==
Minimizes the number of read and swap operations, straight translation of the wikipedia pseudocode:
Minimizes the number of read and swap operations, straight translation of the wikipedia pseudocode:
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">three_way_partition</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">mid</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">three_way_partition</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">mid</span><span style="color: #0000FF;">)</span>
Line 2,800: Line 2,800:
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Unsorted"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">unsorted</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Unsorted"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">unsorted</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Sorted"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sorted</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Sorted"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sorted</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
<small>I thought of unsorted=shuffle(unsorted) in the "oops" loop, but of course that'd repeat forever should they all be the same colour.</small>
<small>I thought of unsorted=shuffle(unsorted) in the "oops" loop, but of course that'd repeat forever should they all be the same colour.</small>
{{out}}
{{out}}
Line 2,809: Line 2,809:


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
_ = random2(), % random seed
_ = random2(), % random seed
N = 21,
N = 21,
Line 2,832: Line 2,832:
dutch_sort(L,MapInv) = [R : _=R in [MapInv.get(R)=R : R in L].sort()].
dutch_sort(L,MapInv) = [R : _=R in [MapInv.get(R)=R : R in L].sort()].


inverse(Map) = new_map([V=K : K=V in Map]).</lang>
inverse(Map) = new_map([V=K : K=V in Map]).</syntaxhighlight>


{{out}}
{{out}}
Line 2,839: Line 2,839:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(def 'Colors
<syntaxhighlight lang="picolisp">(def 'Colors
(list
(list
(def 'RED 1)
(def 'RED 1)
Line 2,851: Line 2,851:
(prin "Sorted balls ")
(prin "Sorted balls ")
(print S)
(print S)
(prinl " are sorted") )</lang>
(prinl " are sorted") )</syntaxhighlight>
{{out}}
{{out}}
<pre>Original balls (RED BLUE WHITE BLUE BLUE RED WHITE WHITE WHITE) not sorted
<pre>Original balls (RED BLUE WHITE BLUE BLUE RED WHITE WHITE WHITE) not sorted
Line 2,858: Line 2,858:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
$Colors = 'red', 'white','blue'
$Colors = 'red', 'white','blue'
Line 2,875: Line 2,875:
''
''
$SortedBalls
$SortedBalls
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,904: Line 2,904:
Works with SWI-Prolog 6.1.11
Works with SWI-Prolog 6.1.11
===Prolog spirit===
===Prolog spirit===
<lang Prolog>dutch_flag(N) :-
<syntaxhighlight lang="prolog">dutch_flag(N) :-
length(L, N),
length(L, N),
repeat,
repeat,
Line 2,963: Line 2,963:


is_dutch_flag_blue([]).
is_dutch_flag_blue([]).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre> ?- dutch_flag(20).
<pre> ?- dutch_flag(20).
Line 2,976: Line 2,976:
===Functional spirit===
===Functional spirit===
Use of filters.
Use of filters.
<lang Prolog>dutch_flag(N) :-
<syntaxhighlight lang="prolog">dutch_flag(N) :-
length(L, N),
length(L, N),


Line 3,038: Line 3,038:


is_dutch_flag_blue([]).
is_dutch_flag_blue([]).
</syntaxhighlight>
</lang>


=={{header|Python}}==
=={{header|Python}}==
===Python: Sorted===
===Python: Sorted===
The heart of the idiomatic Dutch sort in python is the call to function <code>sorted</code> in function <code>dutch_flag_sort</code>.
The heart of the idiomatic Dutch sort in python is the call to function <code>sorted</code> in function <code>dutch_flag_sort</code>.
<lang python>import random
<syntaxhighlight lang="python">import random


colours_in_order = 'Red White Blue'.split()
colours_in_order = 'Red White Blue'.split()
Line 3,077: Line 3,077:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{out|Sample output}}
{{out|Sample output}}
<pre>Original Ball order: ['Red', 'Red', 'Blue', 'Blue', 'Blue', 'Red', 'Red', 'Red', 'White', 'Blue']
<pre>Original Ball order: ['Red', 'Red', 'Blue', 'Blue', 'Blue', 'Red', 'Red', 'Red', 'White', 'Blue']
Line 3,087: Line 3,087:


Replace the function/function call dutch_flag_sort above, with dutch_flag_sort2 defined as:
Replace the function/function call dutch_flag_sort above, with dutch_flag_sort2 defined as:
<lang python>from itertools import chain
<syntaxhighlight lang="python">from itertools import chain
def dutch_flag_sort2(items, order=colours_in_order):
def dutch_flag_sort2(items, order=colours_in_order):
'return summed filter of items using the given order'
'return summed filter of items using the given order'
return list(chain.from_iterable(filter(lambda c: c==colour, items)
return list(chain.from_iterable(filter(lambda c: c==colour, items)
for colour in order))</lang>
for colour in order))</syntaxhighlight>


Or equivalently using a list comprehension (though perhaps less clear):
Or equivalently using a list comprehension (though perhaps less clear):
<lang python>def dutch_flag_sort2(items, order=colours_in_order):
<syntaxhighlight lang="python">def dutch_flag_sort2(items, order=colours_in_order):
'return summed filter of items using the given order'
'return summed filter of items using the given order'
return [c for colour in order for c in items if c==colour]</lang>
return [c for colour in order for c in items if c==colour]</syntaxhighlight>
Output follows that of the sorting solution above.
Output follows that of the sorting solution above.


Line 3,103: Line 3,103:


Replace the function/function call dutch_flag_sort above, with dutch_flag_sort3 defined as:
Replace the function/function call dutch_flag_sort above, with dutch_flag_sort3 defined as:
<lang python>def dutch_flag_sort3(items, order=colours_in_order):
<syntaxhighlight lang="python">def dutch_flag_sort3(items, order=colours_in_order):
'counts each colour to construct flag'
'counts each colour to construct flag'
return sum([[colour] * items.count(colour) for colour in order], [])</lang>
return sum([[colour] * items.count(colour) for colour in order], [])</syntaxhighlight>
Output follows that of the sorting solution above.
Output follows that of the sorting solution above.


===Python: Explicit in-place sort===
===Python: Explicit in-place sort===
<lang python>import random
<syntaxhighlight lang="python">import random


colours_in_order = 'Red White Blue'.split()
colours_in_order = 'Red White Blue'.split()
Line 3,158: Line 3,158:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
Output follows that of the sorting solution above.
Output follows that of the sorting solution above.


=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 3,199: Line 3,199:
balls sorted (if (dutch-order? sorted) 'OK 'BAD)))
balls sorted (if (dutch-order? sorted) 'OK 'BAD)))
(for-each test (list sort-balls/key sort-balls/compare))
(for-each test (list sort-balls/key sort-balls/compare))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,216: Line 3,216:
(formerly Perl 6)
(formerly Perl 6)
Here are five ways to do it, all one liners (apart from the test apparatus).
Here are five ways to do it, all one liners (apart from the test apparatus).
<lang perl6>enum NL <red white blue>;
<syntaxhighlight lang="raku" line>enum NL <red white blue>;
my @colors;
my @colors;


Line 3,245: Line 3,245:


say "Using multiple greps";
say "Using multiple greps";
how'bout { @colors = flat (.grep(red), .grep(white), .grep(blue) given @colors) }</lang>
how'bout { @colors = flat (.grep(red), .grep(white), .grep(blue) given @colors) }</syntaxhighlight>
{{out}}
{{out}}
<pre>Using functional sort
<pre>Using functional sort
Line 3,283: Line 3,283:
The REXX solution could've been simplified somewhat by the use of the &nbsp; '''countstr''' &nbsp; BIF &nbsp; (but some older REXX interpreters don't have).
The REXX solution could've been simplified somewhat by the use of the &nbsp; '''countstr''' &nbsp; BIF &nbsp; (but some older REXX interpreters don't have).


<lang rexx>/*REXX program reorders a set of random colored balls into a correct order, which is the*/
<syntaxhighlight lang="rexx">/*REXX program reorders a set of random colored balls into a correct order, which is the*/
/*────────────────────────────────── order of colors on the Dutch flag: red white blue.*/
/*────────────────────────────────── order of colors on the Dutch flag: red white blue.*/
parse arg N colors /*obtain optional arguments from the CL*/
parse arg N colors /*obtain optional arguments from the CL*/
Line 3,314: Line 3,314:
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
countWords: procedure; parse arg ?,hay; s=1
countWords: procedure; parse arg ?,hay; s=1
do r=0 until _==0; _=wordpos(?, hay, s); s=_+1; end /*r*/; return r</lang>
do r=0 until _==0; _=wordpos(?, hay, s); s=_+1; end /*r*/; return r</syntaxhighlight>
'''output''' &nbsp; when using the default input:
'''output''' &nbsp; when using the default input:
<pre>
<pre>
Line 3,331: Line 3,331:


===colors (as letters)===
===colors (as letters)===
<lang rexx>/*REXX program reorders a set of random colored balls into a correct order, which is the*/
<syntaxhighlight lang="rexx">/*REXX program reorders a set of random colored balls into a correct order, which is the*/
/*────────────────────────────────── order of colors on the Dutch flag: red white blue.*/
/*────────────────────────────────── order of colors on the Dutch flag: red white blue.*/
parse arg N colors /*obtain optional arguments from the CL*/
parse arg N colors /*obtain optional arguments from the CL*/
Line 3,359: Line 3,359:
say
say
say 'The sorted colored ball list has been confirmed as being sorted correctly.'
say 'The sorted colored ball list has been confirmed as being sorted correctly.'
exit /*stick a fork in it, we're all done. */</lang>
exit /*stick a fork in it, we're all done. */</syntaxhighlight>
'''output''' &nbsp; when using the default input:
'''output''' &nbsp; when using the default input:
<pre>
<pre>
Line 3,376: Line 3,376:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Dutch national flag problem
# Project : Dutch national flag problem


Line 3,399: Line 3,399:
next
next
next
next
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,407: Line 3,407:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>class Ball
<syntaxhighlight lang="ruby">class Ball
FLAG = {red: 1, white: 2, blue: 3}
FLAG = {red: 1, white: 2, blue: 3}
Line 3,432: Line 3,432:
puts "Random: #{balls}"
puts "Random: #{balls}"
puts "Sorted: #{balls.sort}"
puts "Sorted: #{balls.sort}"
</lang>
</syntaxhighlight>
{{out}}
{{out}}
<pre>Random: [blue, red, red, red, blue, blue, white, red]
<pre>Random: [blue, red, red, red, blue, blue, white, red]
Line 3,439: Line 3,439:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>flag$ = "Red,White,Blue"
<syntaxhighlight lang="runbasic">flag$ = "Red,White,Blue"


print "Random: |";
print "Random: |";
Line 3,456: Line 3,456:
end if
end if
next j
next j
next i</lang>
next i</syntaxhighlight>
<pre>Random: |White |Blue |White |Red |Red |White |Red |Blue |Red |White |
<pre>Random: |White |Blue |White |Red |Red |White |Red |Blue |Red |White |
Sorted: |Red |Red |Red |Red |White |White |White |White |Blue |Blue |</pre>
Sorted: |Red |Red |Red |Red |White |White |White |White |Blue |Blue |</pre>
Line 3,462: Line 3,462:
=={{header|Rust}}==
=={{header|Rust}}==
{{libheader|rand}}
{{libheader|rand}}
<lang rust>extern crate rand;
<syntaxhighlight lang="rust">extern crate rand;


use rand::Rng;
use rand::Rng;
Line 3,505: Line 3,505:
println!("Oops, did not sort colors correctly!");
println!("Oops, did not sort colors correctly!");
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>object FlagColor extends Enumeration {
<syntaxhighlight lang="scala">object FlagColor extends Enumeration {
type FlagColor = Value
type FlagColor = Value
val Red, White, Blue = Value
val Red, White, Blue = Value
Line 3,518: Line 3,518:


println(s"Generated balls (${genBalls mkString " "}) are $sorted.")
println(s"Generated balls (${genBalls mkString " "}) are $sorted.")
println(s"Sorted balls (${sortedBalls mkString " "}) are sorted.")</lang>
println(s"Sorted balls (${sortedBalls mkString " "}) are sorted.")</syntaxhighlight>


{{out}}
{{out}}
Line 3,525: Line 3,525:


=={{header|SQL}}==
=={{header|SQL}}==
<lang SQL>-- Create and populate tables
<syntaxhighlight lang="sql">-- Create and populate tables
create table colours (id integer primary key, name varchar(5));
create table colours (id integer primary key, name varchar(5));
insert into colours (id, name) values ( 1, 'red' );
insert into colours (id, name) values ( 1, 'red' );
Line 3,559: Line 3,559:
-- Tidy up
-- Tidy up
drop table balls;
drop table balls;
drop table colours;</lang>
drop table colours;</syntaxhighlight>
{{out}}
{{out}}
<pre>COLOUR
<pre>COLOUR
Line 3,589: Line 3,589:
=={{header|Tcl}}==
=={{header|Tcl}}==
This isn't very efficient in terms of the sorting itself (and it happens to use <code>lsearch</code> twice in the comparator!) but it is very simple to write like this.
This isn't very efficient in terms of the sorting itself (and it happens to use <code>lsearch</code> twice in the comparator!) but it is very simple to write like this.
<lang tcl># The comparison function
<syntaxhighlight lang="tcl"># The comparison function
proc dutchflagcompare {a b} {
proc dutchflagcompare {a b} {
set colors {red white blue}
set colors {red white blue}
Line 3,618: Line 3,618:
} else {
} else {
puts "sort failed\n$sorted"
puts "sort failed\n$sorted"
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,627: Line 3,627:
=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
This version is based on Edsger Dijkstra's original algorithm. The flag may come out a bit shredded , but it has been assembled the correct way.
This version is based on Edsger Dijkstra's original algorithm. The flag may come out a bit shredded , but it has been assembled the correct way.
<lang>s = 100
<syntaxhighlight lang="text">s = 100


For x = 0 To s-1
For x = 0 To s-1
Line 3,658: Line 3,658:
Next
Next


Print</lang>
Print</syntaxhighlight>
{{Out}}
{{Out}}
<pre>RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
<pre>RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
Line 3,667: Line 3,667:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bash}}
{{works with|Bash}}
<lang bash>COLORS=(red white blue)
<syntaxhighlight lang="bash">COLORS=(red white blue)


# to go from name to number, we make variables out of the color names
# to go from name to number, we make variables out of the color names
Line 3,724: Line 3,724:
done
done
echo "${a[@]}"
echo "${a[@]}"
}</lang>
}</syntaxhighlight>


Test code:
Test code:
<lang bash>declare -i len=${1:-10}
<syntaxhighlight lang="bash">declare -i len=${1:-10}
balls=()
balls=()
while (( ${#balls[@]} < len )) || dutch? "${balls[@]}"; do
while (( ${#balls[@]} < len )) || dutch? "${balls[@]}"; do
Line 3,734: Line 3,734:
echo "Initial list: ${balls[@]}"
echo "Initial list: ${balls[@]}"
balls=($(dutch "${balls[@]}"))
balls=($(dutch "${balls[@]}"))
echo "Sorted: ${balls[@]}"</lang>
echo "Sorted: ${balls[@]}"</syntaxhighlight>


{{out}}
{{out}}
Line 3,741: Line 3,741:


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
'Solution derived from http://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/.
'Solution derived from http://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/.


Line 3,786: Line 3,786:
WScript.StdOut.Write "Sorted: " & sort(unsort)
WScript.StdOut.Write "Sorted: " & sort(unsort)
WScript.StdOut.WriteLine
WScript.StdOut.WriteLine
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 3,796: Line 3,796:
=={{header|Visual FoxPro}}==
=={{header|Visual FoxPro}}==
===SQL Version===
===SQL Version===
<lang vfp>
<syntaxhighlight lang="vfp">
CLOSE DATABASES ALL
CLOSE DATABASES ALL
LOCAL lcCollate As String, i As Integer, n As Integer
LOCAL lcCollate As String, i As Integer, n As Integer
Line 3,831: Line 3,831:
RETURN INT(3*RAND()) + 1
RETURN INT(3*RAND()) + 1
ENDFUNC
ENDFUNC
</syntaxhighlight>
</lang>
===Array Version===
===Array Version===
<lang vfp>
<syntaxhighlight lang="vfp">
LOCAL i As Integer, n As Integer, colours As String, k As Integer
LOCAL i As Integer, n As Integer, colours As String, k As Integer
colours = "Red,White,Blue"
colours = "Red,White,Blue"
Line 3,869: Line 3,869:
RETURN INT(3*RAND()) + 1
RETURN INT(3*RAND()) + 1
ENDFUNC
ENDFUNC
</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-sort}}
{{libheader|Wren-sort}}
<lang ecmascript>import "random" for Random
<syntaxhighlight lang="ecmascript">import "random" for Random
import "/sort" for Sort
import "/sort" for Sort


Line 3,890: Line 3,890:
System.print("Before sorting : %(balls)")
System.print("Before sorting : %(balls)")
Sort.insertion(balls, colorCmp)
Sort.insertion(balls, colorCmp)
System.print("After sorting : %(balls)")</lang>
System.print("After sorting : %(balls)")</syntaxhighlight>


{{out}}
{{out}}
Line 3,900: Line 3,900:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>const RED=0, WHITE=1, BLUE=2; var BALLS=T(RED,WHITE,BLUE);
<syntaxhighlight lang="zkl">const RED=0, WHITE=1, BLUE=2; var BALLS=T(RED,WHITE,BLUE);
fcn colorBalls(balls){ balls.apply(T("red","white","blue").get).concat(", "); }
fcn colorBalls(balls){ balls.apply(T("red","white","blue").get).concat(", "); }


Line 3,909: Line 3,909:
}while(balls==sortedBalls); // make sure sort does something
}while(balls==sortedBalls); // make sure sort does something
println("Original ball order:\n", colorBalls(balls));
println("Original ball order:\n", colorBalls(balls));
println("\nSorted ball order:\n", colorBalls(sortedBalls));</lang>
println("\nSorted ball order:\n", colorBalls(sortedBalls));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,921: Line 3,921:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
{{trans|Run_BASIC}}
{{trans|Run_BASIC}}
<lang zxbasic>10 LET r$="Red": LET w$="White": LET b$="Blue"
<syntaxhighlight lang="zxbasic">10 LET r$="Red": LET w$="White": LET b$="Blue"
20 LET c$="RWB"
20 LET c$="RWB"
30 DIM b(10)
30 DIM b(10)
Line 3,934: Line 3,934:
120 IF b(j)=i THEN PRINT VAL$ (c$(i)+"$");" ";
120 IF b(j)=i THEN PRINT VAL$ (c$(i)+"$");" ";
130 NEXT j
130 NEXT j
140 NEXT i</lang>
140 NEXT i</syntaxhighlight>