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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with list-element manipulation 1

Status
Not open for further replies.

pillow1

Programmer
Feb 8, 2007
1
SE
Hi!

I want to remove elements in a list, that fulfill certain criteria. That is, in a list, I want to be able to remove all integers that are divisible by a given number N, which I like to give as input. In the example below N = 2.

listDivByN([1,2,3,4,5], 2, List).

should result in:

List = [1,3,5]

So far, I have managed to get a result like this: List = [1,0,1,0,1]. So my problem is that I can't remove the elements that are divisible by N. And 5 divsible with 2 shouldn't result in 1, because that is the remainder. It should result in 5.

Does anybody know how to do this ? I'm new to Prolog, and I would appreciate if someone could help me.

Thx!
 

%---------------------------------

%0 for even numbers.
par(X,Y):-Y is X mod 2.

%---------------------------
%calculates the remaining of each number from the list.
%ie lstpar([1,2,3,4,5],S).

lstpar([E|_],[S,E]):par(E,S).
lstpar([_|T],S):-lstpar(T,S).

%----------------------------
%even numbers and odd number
%ie pares([1,2,3,4,5],R).

pares(L,R):-findall(S,(lstpar(L,S),member(0,S)),C),
secondsL(C,R).


impares(L,R):-findall(S,(lstpar(L,S),\+member(0,S)),C),
secondsL(C,R).

%-------------------
% solve the problem
%i.e listDivByN([1,2,3,4,5],2,I).

listDivByN(L,N,I):par(N,B),add(B,[],R),member(1,R),pares(L,I).
listDivByN(L,N,I):par(N,B),add(B,[],R),\+member(1,R),impares(L,I).


%-----------------
%helper predicates
%inserts in the beginning of the list
add(X,L,[X|L]).

%seconds of each list
secondsL([],[]):-!.
secondsL([[]|X],X):-!.
secondsL([[_,T]|R],[T|S]):-secondsL(R,S).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top