Sunday, 16 June 2019

Write a program for list manipulation using arithmetic and comparison operators.

1.  Find maximum number out of LIST of numbers
maxl([M|[]],M).
maxl([H|T],M):-
maxl(T,M1), H>M1,
M is H. maxl([H|T],M):-
maxl(T,M1), H<M1,
M is M1.

Input: maxl([8,6,4,2],X).
Output: X = 8

2.  Find minimum number out of LIST of numbers

minl([M|[]],M).
minl([H|T],M):-
minl(T,M1), H<M1,
M is H. minl([H|T],M):-
minl(T,M1), H>M1,
M is M1.

Input: maxl([8,6,4,2],X).
Output: X = 2

3.  Sort the given LIST in ascending order

bubblesort(L, L1) :- (bubble(L, L2)
-> bubblesort(L2, L1)
; L = L1 ).

bubble([A, B|T], L) :- ( A > B
-> L = [B, A|T]
; L = [A | L1],
bubble([B|T], L1)).
Input: bubblesort([8,6,4,2],X).
Output: X = [2, 4, 6, 8].

4.  Sort given list in descending order

bubblesort(L, L1) :- (bubble(L, L2)
-> bubblesort(L2, L1)
; L = L1 ).

bubble([A, B|T], L) :- ( A < B
-> L = [B, A|T]
; L = [A | L1],
bubble([B|T], L1)).

Input: bubblesort([8,6,4,2],X).
Output: X = [8, 6, 4, 2].

5.  Add two lists and store result in third list.

list_sum([],[],[]).
list_sum([H1|T1],[H2|T2],[X|L3]):- list_sum(T1,T2,L3),
X is H1+H2.

Input: list_sum([1,2,3],[4,5,6],X).
Output: X = [5, 7, 9].

6.  Apply subtraction between TWO lists and store result in third list.

list_sub([],[],[]).
list_sub([H1|T1],[H2|T2],[X|L3]):- list_sub(T1,T2,L3),
X is H1-H2.

Input: list_sub([9,6,3],[4,5,6],X).
Output: X = [5, 1, -3].

7.  Apply multiplication between TWO lists and store result in third list.

list_mul([],[],[]).
list_mul([H1|T1],[H2|T2],[X|L3]):- list_mul(T1,T2,L3),
X is H1*H2.
Input: list_sub([9,6,3],[4,5,6],X).
Output: X = [36, 30, 18].

No comments:

Post a Comment

It's time To increase blogging capability. To have a chance to contribute in digital world. Any Interested People who want to make t...