检查一个国家是否需要获得关键数量的选票

Check if a country is needed for a critical amount of votes

大家好,我是 prolog 的新手,正在自学。 我在网上找到了这个问题,但没有任何答案。

我有这个数据库

countries([belgium, france, germany, italy, luxembourg, netherlands]). 

weight(france, 4). 
weight(germany, 4).
weight(italy, 4). 
weight(belgium, 2). 
weight(netherlands, 2). 
weight(luxembourg, 1). 
threshold(12).

现在我制作了这个程序来查看国家列表是否有足够的票数来超过门槛。

winning([], 0).

winning([Head | Tail], N):-
    weight(Head, N1),
    winning(Tail, N2),
    N is N1 + N2.

winning(Y):-
    winning(Y, N),      
    threshold(X),
    N >= X. 

现在我需要写一个程序critical/2,第一个参数是一个国家,第二个参数是一个国家列表。是否需要第一个超过门槛的国家。

示例:

?- critical(netherlands, [belgium, france, germany]). 
   True
?- critical(netherlands, [france, germany, italy]). 
   False

对于这个程序,我需要先检查第二个参数是否已经获胜。如果是这样,它将失败。如果不是,我需要获取第一个参数的值,将其添加到第二个值,然后检查它是否超过阈值。如果不够,它将失败。够了就成功。

 critical(X,Y):-
    winning(Y,N),
    weight(X,Value),
    N1 is N+Value,
    threshold(X),
    N1 >= X.

我在这里做错了很多事情,但我不知道如何解决。

您已经非常接近解决方案了。一些提示:

首先,良好的命名约定可以帮助您了解哪个参数是什么:

critical(C, Cs) :-

这表明第一个参数是一个国家,第二个是零个或多个国家的列表。

所以,让我们首先将 Cs 与它们的总重量联系起来。同样,它有助于有一个好的命名约定,明确哪个参数是什么:

country_weight(france,      4). 
country_weight(germany,     4).
country_weight(italy,       4). 
country_weight(belgium,     2). 
country_weight(netherlands, 2). 
country_weight(luxembourg,  1)

现在,为了将多个国家与其各自的权重相关联,我们使用元谓词 maplist/3:

maplist(country_weight, Cs, Ws)

为了求和权重,我们使用 sum_list/2:

sum_list(Ws, Sum)

如何描述Sum必须低于阈值是显而易见的(留作练习)。

最后,为了表示第一个参数表示的国家的权重加上的总和大于阈值,我们使用:

country_weight(C, W),
W + Sum > Threshold

定义到此结束。请注意,根本没有必要描述哪些国家存在。因此,您可以省略程序的第一个谓词。