gpt4 book ai didi

prolog - 如何使用clpfd :automaton to restrict counter value in SICStus Prolog?

转载 作者:行者123 更新时间:2023-12-04 02:50:55 26 4
gpt4 key购买 nike

我想实现一个非常简单的自动机,它限制 1 和 0 列表中连续 1 的数量(例如 [0,1,1,0,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 代码?

最佳答案

最好用附加状态来表述它。例如,对于最多两个连续的 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.

对于更通用的解决方案,您必须在给定最大运行长度时按需构建自动机。

关于prolog - 如何使用clpfd :automaton to restrict counter value in SICStus Prolog?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17770356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com