Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

List processing, Please help.... 1

Status
Not open for further replies.

abimaran

Programmer
Apr 2, 2010
1
LK
Consider the digits: 1234567890. First remove one digit, then swap two adjacent digits and
then insert some number of plus signs between the digits. There is a way to do this so that
the answer to the resulting arithmetic expression is 2004!
Hints:
You should define the digits as a list in your code, i.e. put the fact:
digits([1,2,3,4,5,6,7,8,9,0]) in your program.


How to do? Where to start?
 
The solution is: 1245+679+80
Missing digit = 3
Swapped digits = 8 and 9
Two plus signs added as shown above

Prolog code that solves this problem:

digits([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).


% remove(L, R) - removes an element of L, resulting R
remove(L, R) :-
member(X, L),
delete(L, X, R).


% swap(L, R) - swaps two elements in L, resulting R
swap(L, R) :-
append(L1, [A, B | L2], L),
append(L1, [B, A | L2], R).

% insert(L, R) - inserts any number of plus signs between
% elements in L, resulting R
insert([], []).
insert([H | T], [H, '+' | T1]) :-
T \= [],
insert(T, T1).
insert([H | T], [H | T1]) :-
insert(T, T1).


% decimal(L, X, N) - if L contains no '+' signs, computes
% in N the decimal value of L. X should be 0 at first call
decimal([], N, N).
decimal([H|T], Current, X) :-
Current1 is 10 * Current + H,
decimal(T, Current1, X).


% value(L, X) - computes in X the value of list L; there
% can be '+' signs in L, the computation is aware of them
value(L, X) :-
\+member('+', L),!,
decimal(L, 0, X).
value(L, X) :-
append(L1, ['+' | L2], L),!,
decimal(L1, 0, A),
value(L2, B),
X is A + B.


% writelist(L) - writes list L without the '[' and ']'
writelist([]).
writelist([H|T]) :-
write(H),writelist(T).


% solve(R) - main predicate
solve(R) :-
digits(L),
remove(L, L1),
swap(L1, L2),
insert(L2, R),
value(R, 2004),
writelist(R),
nl.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top