Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog program that deletes every n-th element from a list

Tags:

list

prolog

Could you help me solve the following?

Write a ternary predicate delete_nth that deletes every n-th element from a list.

Sample runs:

?‐ delete_nth([a,b,c,d,e,f],2,L).
L = [a, c, e] ;
false
?‐ delete_nth([a,b,c,d,e,f],1,L).
L = [] ;
false
?‐ delete_nth([a,b,c,d,e,f],0,L).
false

I tried this:

listnum([],0).
listnum([_|L],N) :-
   listnum(L,N1),
   N is N1+1.

delete_nth([],_,_).
delete_nth([X|L],C,L1) :- 
   listnum(L,S),
   Num is S+1,
   (  C>0
   -> Y is round(Num/C),Y=0
   -> delete_nth(L,C,L1)
   ;  delete_nth(L,C,[X|L1])
   ).
like image 572
user3598120 Avatar asked Dec 15 '22 23:12

user3598120


1 Answers

My slightly extravagant variant:

delete_nth(L, N, R) :-
    N > 0, % Added to conform "?‐ delete_nth([a,b,c,d,e,f],0,L). false"
    ( N1 is N - 1, length(Begin, N1), append(Begin, [_|Rest], L) ->
        delete_nth(Rest, N, RestNew), append(Begin, RestNew, R)
    ;
        R = L
    ).
like image 171
Sergii Dymchenko Avatar answered May 03 '23 01:05

Sergii Dymchenko