2

我目前正在编写一个,它采用 [0,1]* 形式的列表,并告诉我0列表中 ' 的数量是否3大于1' 的数量。我似乎无法让第三部分 ( dcg//0) 工作。

 sq --> [].
 sq --> num, sq.

 num --> [0].
 num --> [1].

 dcg --> sq, dd(Count), Count > 2.

 dd(0) --> [].
 dd(Newcnt) --> [0], dd(Cnt), { Newcnt is Cnt+1 }.
 dd(Newcnt) --> [1], dd(Cnt), { Newcnt is Cnt-1 }.
4

3 回答 3

1

@Little Bobby Tables 的答案合成(计数)元素编号,并且在 DCG 之外,您需要测试结果

..., phrase(sq(Z,O), S), Z is O*3, ...

一种更简单的方法可能是传递不平衡

z3o1(B) --> [1], {S is B-3}, z3o1(S).
z3o1(B) --> [0], {S is B+1}, z3o1(S).
z3o1(0) --> [].  % accept only if balanced

..., phrase(z3o1(0), S), ...
于 2012-11-28T09:57:56.900 回答
1

快到了……其实代码已经有了,我们来使用吧!

:- use_module(library(clpfd)).

运行我们得到dd//1phrase/2

?- C #>= 3, phrase(dd(C), Xs).
   C = 3, Xs = [0,0,0]
;  C = 4, Xs = [0,0,0,0]
;  C = 5, Xs = [0,0,0,0,0]
;  C = 6, Xs = [0,0,0,0,0,0]
;  C = 7, Xs = [0,0,0,0,0,0,0]
;  C = 8, Xs = [0,0,0,0,0,0,0,0]
;  C = 9, Xs = [0,0,0,0,0,0,0,0,0]
...

序列包含在哪里1?我们知道它们必须存在......

?- Xs = [0,0,0,1,0], C #>= 3, 短语(dd(C), Xs)。
   Xs = [0,0,0,1,0],C = 3
; 错误的。

...但它们没有出现在上述答案序列中:

?- C#>= 3, 短语(dd(C), Xs), Xs = [0,0,0,1,0]。
**循环**

为了强制对解决方案集进行公平枚举,我们可以使用length/2如下目标:

?- C#>= 3,长度(Xs,_),短语(dd(C),Xs)。
   C = 3,Xs = [0,0,0]
; C = 4,Xs = [0,0,0,0]
; C = 5,Xs = [0,0,0,0,0]
; C = 3,Xs = [0,0,0,0,1]
;  C = 3,Xs = [0,0,0,1,0]
; C = 3,Xs = [0,0,1,0,0]
; C = 3,Xs = [0,1,0,0,0]
; C = 3,Xs = [1,0,0,0,0]
; C = 6,Xs = [0,0,0,0,0,0]
...
于 2016-01-15T10:22:53.073 回答
0

以下代码计算给定序列中零和一的数量。您可以使用它来应用您想要的任何条件。

sq(0, 0) --> [].
sq(Zeros, Ones) -->
    [0], 
    sq(Z, Ones), 
    {Zeros is Z + 1}.
sq(Zeros, Ones) -->
    [1], 
    sq(Zeros, O),
    {Ones is O + 1}.
于 2012-11-28T07:19:08.343 回答