Jump to content

Number reversal game: Difference between revisions

Added Prolog
No edit summary
(Added Prolog)
Line 2,851:
"Your score: $nTries"
</lang>
 
=={{header|Prolog}}==
<lang Prolog>play :- random_numbers(L), do_turn(0,L), !.
 
do_turn(N, L) :-
print_list(L),
how_many_to_flip(F),
flip(L,F,[],Lnew),
succ(N,N1),
sorted(N1,Lnew).
 
how_many_to_flip(F) :-
read_line_to_codes(user_input, Line),
number_codes(F, Line),
between(1,9,F).
flip(L,0,C,R) :- append(C,L,R).
flip([Ln|T],N,C,R) :- dif(N,0), succ(N0,N), flip(T,N0,[Ln|C],R).
sorted(N,L) :-
sort(L,L)
-> print_list(L), format('-> ~p~n', N)
; do_turn(N,L).
 
random_numbers(L) :- random_permutation([1,2,3,4,5,6,7,8,9],L).
 
print_list(L) :-
atomic_list_concat(L, ' ', Lf),
format('(~w) ',Lf).</lang>
{{out}}
<pre>
?- play.
(5 1 8 4 3 6 7 9 2) 8
(9 7 6 3 4 8 1 5 2) 5
(4 3 6 7 9 8 1 5 2) 6
(8 9 7 6 3 4 1 5 2) 2
(9 8 7 6 3 4 1 5 2) 9
(2 5 1 4 3 6 7 8 9) 2
(5 2 1 4 3 6 7 8 9) 3
(1 2 5 4 3 6 7 8 9) 5
(3 4 5 2 1 6 7 8 9) 2
(4 3 5 2 1 6 7 8 9) 3
(5 3 4 2 1 6 7 8 9) 2
(3 5 4 2 1 6 7 8 9) 3
(4 5 3 2 1 6 7 8 9) 2
(5 4 3 2 1 6 7 8 9) 5
(1 2 3 4 5 6 7 8 9) -> 14
true.
</pre>
 
=={{header|PureBasic}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.