Dutch national flag problem: Difference between revisions
Content added Content deleted
(Added C++ implementation) |
(→{{header|Go}}: Add Erlang.) |
||
Line 220: | Line 220: | ||
</pre> |
</pre> |
||
=={{header|Erlang}}== |
|||
<lang erlang>-module(dutch). |
|||
-export([random_balls/1, is_dutch/1, dutch/1]). |
|||
ball(red) -> 1; |
|||
ball(white) -> 2; |
|||
ball(blue) -> 3. |
|||
random_ball() -> lists:nth(random:uniform(3), [red, white, blue]). |
|||
random_balls(N) -> random_balls(N,[]). |
|||
random_balls(0,L) -> L; |
|||
random_balls(N,L) when N > 0 -> |
|||
B = random_ball(), |
|||
random_balls(N-1, [B|L]). |
|||
is_dutch([]) -> true; |
|||
is_dutch([_]) -> true; |
|||
is_dutch([B|[H|L]]) -> (ball(B) < ball(H)) and is_dutch([H|L]); |
|||
is_dutch(_) -> false. |
|||
dutch(L) -> dutch([],[],[],L). |
|||
dutch(R, W, B, []) -> R ++ W ++ B; |
|||
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, [blue | L]) -> dutch(R, W, [blue|B], L).</lang> |
|||
Sample usage: |
|||
<lang erlang>main(_) -> |
|||
L = random_balls(10), |
|||
case is_dutch(L) of |
|||
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)]) |
|||
end.</lang> |
|||
Sample output: |
|||
<pre>The starting random sequence is [white,white,blue,blue,white,red,white,blue, |
|||
blue,white]; |
|||
The ordered sequence is [red,white,white,white,white,white,blue,blue,blue, |
|||
blue].</pre> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
<lang go>package main |
<lang go>package main |
||
Line 314: | Line 355: | ||
[{0} {0} {0} {1} {1} {1} {1} {1} {2} {2} {2} {2}] |
[{0} {0} {0} {1} {1} {1} {1} {1} {2} {2} {2} {2}] |
||
</pre> |
</pre> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
With the Color data type we take care that no other values than Red, White and Blue can be used. |
With the Color data type we take care that no other values than Red, White and Blue can be used. |