find all k-length subsets of list in prolog

后端 未结 1 1499
眼角桃花
眼角桃花 2021-01-21 02:59

i need to find a k-length subset of list in prolog, i have this function:

    subset([], []).
    subset([E|Tail], [E|NTail]):-
    subset(Tail, NTail).
    subs         


        
相关标签:
1条回答
  • 2021-01-21 03:41

    Using your initial solution to subset/2, you might add another argument (Len) and:

    • Base case holds when Len = 0
    • Recursive step which adds element decrements Len and finishes recursion if new Len=0

    That would look:

     subset(0, [], []).
     subset(Len, [E|Tail], [E|NTail]):-
       succ(PLen, Len),
       (PLen > 0 -> subset(PLen, Tail, NTail) ; NTail=[]).
     subset(Len, [_|Tail], NTail):-
       subset(Len, Tail, NTail).
    
    0 讨论(0)
提交回复
热议问题