我想实现一个非常简单的自动机来限制1和0列表中的连续1的数量(例如0,1,1,0,1,1,1,1)。
我的自动机看起来像这样:
% 'Day' is a list of clpfd variables
% 'Allowed' is an integer
%
% consecutiveOnes(+Day, +Allowed)
consecutiveOnes(Day, Allowed) :-
automaton(Day, _, Day,
[source(n)],
[
arc(n, 0, n, [0] ),
arc(n, 1, n, [C+1])
],
[C],
[0],
[_N]
).
% example 1:
% consecutiveOnes([0,0,0,1,1,1], 2) -> there are three consecutive 1s and we allow only 2 -> Fail.
% example 2:
% consecutiveOnes([0,1,1,1,0,0], 2) -> there are three consecutive 1s and we allow only 2 -> Fail.
% example 3:
% consecutiveOnes([0,1,1,0,0,0], 2) -> there are only two consecutive 1s and we allow 2 -> OK如何将计数器C指定C <= Allowed的约束添加到上面的Prolog代码中?
发布于 2013-07-21 23:02:21
最好是用额外的状态来表示这一点。例如,对于最多两个连续的1:
:- use_module(library(clpfd)).
at_most_two_consecutive_ones(Day) :-
automaton(Day,
[source(n),sink(n),sink(n1),sink(n2)],
[arc(n, 0, n),
arc(n, 1, n1),
arc(n1, 1, n2),
arc(n1, 0, n),
arc(n2, 1, false),
arc(n2, 0, n)
]).查询示例:
?- at_most_two_consecutive_ones([0,0,0,1,1,1]).
false.
?- at_most_two_consecutive_ones([0,1,1,0,1,1]).
true.
?- at_most_two_consecutive_ones([0,1,1,0,1,0]).
true.对于更一般的解决方案,当给定运行的最大长度时,您必须按需构建自动机。
发布于 2018-06-19 18:15:48
我相信下面的代码就是你要找的:
:- use_module(library(clpfd)).
consecutiveOnes(Day, Allowed) :-
automaton(Day, _, Day,
[source(n),sink(n)],
[
arc(n, 0, n, [0] ),
arc(n, 1, n, (C #< Allowed -> [C+1]))
],
[C],[0],[_N]
).否则,它将拒绝所有序列。(2)增加了C< Allowed的条件。如果条件不满足,则没有其他条件,因此它失败。
以下是一些查询示例:
| ?- consecutiveOnes([0,1,1,0],1).
no
| ?- consecutiveOnes([0,1,1,0],2).
yes
| ?- consecutiveOnes([0,1,1,0,1,1,1],2).
no
| ?- consecutiveOnes([0,1,1,0,1,1,0],2).
yeshttps://stackoverflow.com/questions/17770356
复制相似问题