2

I'm struggling with this one:

Define predicate len_NM(L,N,M) which checks if a certain list of lists L contains at least N elements with length no less than M.

repeat
  • 18,496
  • 4
  • 54
  • 166

1 Answers1

1
  1. The OP stated:

    Define predicate len_NM(L,N,M) which checks if a certain list of lists L contains at least N elements with length no less than M.

  2. In this answer we do not solve the original problem, but the following variation:

    Define predicate len_NM(L,N,M) which checks if a certain list of lists L contains exactly N elements with length no less than M.

  3. Similarly to this answer, we define seqq1//1 to establish the relationship between a list of non-empty lists and its flattened opposite:

    seq([])     --> [].
    seq([E|Es]) --> [E], seq(Es).
    
    seqq1([])       --> [].
    seqq1([Es|Ess]) --> {Es=[_|_]}, seq(Es), seqq1(Ess).
    

    Sample use:

    ?- phrase(seqq1([[1,2],[3],[4]]),Xs).
    Xs = [1,2,3,4].
    

    Note that seqq1//1 works in "both directions":

    ?- phrase(seqq1(Xss),[1,2,3,4]).
      Xss = [[1],[2],[3],[4]] 
    ; Xss = [[1],[2],[3,4]]
    ; Xss = [[1],[2,3],[4]]
    ; Xss = [[1],[2,3,4]]
    ; Xss = [[1,2],[3],[4]]
    ; Xss = [[1,2],[3,4]]
    ; Xss = [[1,2,3],[4]]
    ; Xss = [[1,2,3,4]]
    ; false.
    
  4. In this answer we use :

    :- use_module(library(clpfd)).
    

    Then, we define len_NM/4—using maplist/3, length/2, tcount/3, and (#=<)/3:

    len_NM(Xss,Ys,N,M) :-
       M #>= 1,
       N #>= 0,
       phrase(seqq1(Xss),Ys),
       maplist(length,Xss,Ls),
       tcount(#=<(M),Ls,N).
    

Let's run some sample queries!

?- len_NM([[1,2,3],[4],[5,6],[7,8,9,10],[11,12]],_,N,L).
  N = 5, L = 1             % five lists have length of at least one 
; N = 4, L = 2             % four lists have length of at least two
; N = 2, L = 3             % two of at least three (e.g., [1,2,3] and [7,8,9,10])
; N = 1, L = 4             % one list has length of four (or more)
; N = 0, L in 5..sup.      % no list has length of five (or more)

OK! How about this one?

?- append(Xs,_,[x,x,x,x,x,x]),   % With `Xs` having at most 6 elements ...
   N #>= 1,                      % ... `Xss` shall contain at least 1 list ...
   len_NM(Xss,Xs,N,4).           % ... having a length of 4 (or more).
  Xs = [x,x,x,x],     N = 1, Xss = [[x,x,x,x]]
; Xs = [x,x,x,x,x],   N = 1, Xss = [[x],[x,x,x,x]]
; Xs = [x,x,x,x,x],   N = 1, Xss = [[x,x,x,x],[x]]
; Xs = [x,x,x,x,x],   N = 1, Xss = [[x,x,x,x,x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x],[x],[x,x,x,x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x],[x,x,x,x],[x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x],[x,x,x,x,x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x,x],[x,x,x,x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x,x,x,x],[x],[x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x,x,x,x],[x,x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x,x,x,x,x],[x]]
; Xs = [x,x,x,x,x,x], N = 1, Xss = [[x,x,x,x,x,x]]
; false.
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166