Wednesday, November 24, 2010

Next Higher Permutation on Prolog Programming

delete(X,[X|T],T).
delete(X,[Y|T],[Y|T1]):-del(X,T,T1).

permute([],[]).
permute(L,[X|P]):-delete(X,L,L1),permute(L1,P).
   
greatest([X|T1],[Y|T2]):-X<Y.             
   
greatest([X|R1],[Y|R2]):-X<Y,greatest(R1,R2).

hp(N,N1):-permute(N,N1),greatest(N,N1).
           
nhp(N,N1):-hp(N,N1),hp(N,N2),greatest(N2,N1).
 

25 comments:

  1. really? my result (after correcting del -> delete)

    ?- nhp([1,2,3], N).
    N = [3, 1, 2] ;
    N = [3, 1, 2] ;
    N = [3, 1, 2] ;
    N = [3, 2, 1] ;
    N = [3, 2, 1] ;
    N = [3, 2, 1] ;
    N = [3, 2, 1] ;
    false.


    this is not next higher permutation...

    ReplyDelete
  2. next_higher_permutation(L,L1) :-
    higher_permutation(L,L1),
    not(far_higher_permutation(L1,L)).

    higher_permutation(L,L1) :-
    permutation(L,L1),
    higher(L1,L).

    higher([H1|T1],[H|T]) :- H1 > H ,!.

    higher([H|T1],[H|T]) :- higher(T1,T).

    far_higher_permutation(L1,L) :-
    higher_permutation(L,L2),
    higher(L1,L2).

    permutation([],[]).
    permutation(L,[H|T]) :-
    select(H,L,R),
    permutation(R,T).

    select(X,[X|R],R).
    select(X,[H|R],[H|R1]) :-
    select(X,R,R1).

    ReplyDelete
  3. With over 85+ institutes around the countr, VLCC Institute has been a leader in training students who wish to pursue their careers in the Bridal Makeup Course. Beauty and Wellness space.

    ReplyDelete