How to resolve the algorithm Number reversal game step by step in the Prolog programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Number reversal game step by step in the Prolog programming language

Table of Contents

Problem Statement

Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and 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.

The score is the count of the reversals needed to attain the ascending order.

Note: Assume the player's input does not need extra validation.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Number reversal game step by step in the Prolog programming language

Source code in the prolog programming language

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).


  

You may also check:How to resolve the algorithm Loops/N plus one half step by step in the Lang5 programming language
You may also check:How to resolve the algorithm Sequence of primes by trial division step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Sorting algorithms/Stooge sort step by step in the ooRexx programming language
You may also check:How to resolve the algorithm Old lady swallowed a fly step by step in the Babel programming language
You may also check:How to resolve the algorithm Calculating the value of e step by step in the zkl programming language