'Prolog : Trying to get odd and even upto specific element of list
I want to know how many even and odd numbers are present in the list up to a specific index entered by the user.
The following code is working but only gives either even or odd elements. Can someone help me getting the desired output? Thanks in advance.
:- use_module(library(clpfd)).
oddlength(L):-
L9 is L+2,
L6 is L9/2,
write('List has '),
write(L6),
write(' Odd Element').
evenlength(L):-
L6 is L/2,
write('List has '),
write(L6),
write(' Even Element').
split(Index,List,Left,Right) :-
length(Left,Index), % Actually CREATES a list of fresh variables if "Left" is unbound
append(Left,Right,List). % Demand that Left + Right = List.
write(List).
create(L1):-read(Elem),create(Elem,L1).
create(-1,[]):-!. create(Elem,[Elem|T]):-read(Nextel),create(Nextel,T).
chklst([H|T]):-
length(T,L),
L>=0 ->
(
L1 is L+1,
L2 is mod(L1,2),
L2=:=0 ->
evenlength(L1)
;
oddlength(L)
).
go:- write('Creating a list'),nl, write('Enter -1 to stop'),nl, create(L), nl, write('Enter index'),read(ID),split(ID,L,X1,X2),nl, chklst(X1).
Solution 1:[1]
That seems . . . complicated.
First thing you need is a predicate to test whether an integer is odd or even:
even(N) :- 0 =:= N rem 2 .
Once you have that it's a simple matter of traversing the list.
If all you want are counts:
evens_and_odds( Ns , I, E, O ) :- evens_and_odds( Ns, 0, I, 0 , 0 , E, O ) .
evens_and_odds( [] , _ , _ , E , O , E , O ) . % if we've exhausted the source list, we're done.
evens_and_adds( [N|Ns] , P , P , E , O , E , O ) . % ditto, if we've hit the desired index.
evens_and_odds( [N|Ns] , P , Q , X , Y , E , O ) :- % otherwise....
P < Q , % - we haven't yet hit the target index
P1 is P+1, % - tick the counter
tally(N,X,Y,X1,Y1), % - do the tally
evens_and_odds(Ns,P1,Q,X1,Y1,E,O) % - and recurse down
. % Easy!
tally( N , E , O , E1 , O ) :- even(N), !, E1 is E+1 .
tally( N , E , O , E , O1 ) :- O1 is O+1 .
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nicholas Carey |