Jump to content

Number reversal game: Difference between revisions

Added Erlang
m ('s)
(Added Erlang)
Line 731:
 
You took 9 attempts.</pre>
 
=={{header|Erlang}}==
<lang Erlang>
-module( number_reversal_game ).
 
-export( [task/0, start/1] ).
 
start( N ) when N > 1 ->
io:fwrite( "Usage: ~s~n", [usage(N)] ),
Targets = lists:seq( 1, N ),
Jumbleds = [X||{_,X} <- lists:sort([ {random:uniform(), Y} || Y <- Targets])],
Attempt = loop( Targets, Jumbleds, 0 ),
io:fwrite( "Numbers sorted in ~p atttempts~n", [Attempt] ).
 
task() -> start( 9 ).
 
 
 
loop( Targets, Targets, Attempt ) -> Attempt;
loop( Targets, Jumbleds, Attempt ) ->
io:fwrite( "~p~n", [Jumbleds] ),
{ok,[N]} = io:fread( "How many digits from the left to reverse? ", "~d" ),
{Lefts, Rights} = lists:split( N, Jumbleds ),
loop( Targets, lists:reverse(Lefts) ++ Rights, Attempt + 1 ).
 
usage(N) -> io_lib:format( "Given a jumbled list of the numbers 1 to ~p that are definitely not in ascending order, show the list then ask the player how many digits from the left to reverse. Reverse those digits, then ask again, until all the digits end up in ascending order.", [N] ).
</lang>
{{out}}
Not being a very good player I show a test run with only 3 numbers.
<pre>
35> number_reversal_game:start(3).
Usage: Given a jumbled list of the numbers 1 to 3 that are definitely not in ascending order, show
the list then ask the player how many digits from the left to reverse. Reverse those digits, then
ask again, until all the digits end up in ascending order.
[2,3,1]
How many digits from the left to reverse? 3
[1,3,2]
How many digits from the left to reverse? 3
[2,3,1]
How many digits from the left to reverse? 2
[3,2,1]
How many digits from the left to reverse? 3
Numbers sorted in 4 atttempts
</pre>
 
=={{header|Euphoria}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.