作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下数据集:
food_a(bagel, 245).
food_a(sandwich, 200).
food_a(salad,300).
food(bagel).
food(sandwich).
food(salad).
我想满足以下约束:给定总卡路里数,我想返回满足该限制的食品。例如。总卡路里计数 = 500,程序应返回“百吉饼+三明治”作为解决方案。我按照 clingo 代码对他进行了编码:
food_a(bagel, 245).
food_a(sandwich, 200).
food_a(salad,300).
food(bagel).
food(sandwich).
food(salad).
has(bagel, wheat).
has(sandwich, bread).
has(sandwich, tomatoes).
has(sandwich, onion).
has(sandwich, cheese).
%calories(food,amount):-food_a(food,amount).
%food(F):-food_a(F,C).
%limits(calories,200).
%sol(F) :- food_a(F,C1),food_a(F,C2), C1+C2<500.
%:- {food(F,C) : food_a(F,C1),food_a(F,C2)} , C1+C2 >500.
%food_diet(F) :- food(F,C), C<250.
%:- food(F1) ,food_a(F2,C2), C1+C2=445.
totals(P, S) :- S = #sum{ I : food_a(P,I)}, food(P), S<500.
显然,该程序只返回单一食物,而不是一次考虑 2 或 3 个食物的组合。任何人都可以建议我必须遵循的更改或步骤才能实现相同的目标。
最佳答案
您目前正在分别计算每种食物的总和。如果您对同一种食物有多个值,例如food_a(bagel, 100)
和 food_a(bagel, 200)
那么结果将是 total(bagel, 300)
。本质上,由于每种食物只有一个 food_a/2
,因此您的 totals/2
定义相当于
totals(P, S) :- food_a(P, S), food(P), S<500.
你想要的是这样的
food_a(bagel, 245).
food_a(sandwich, 200).
food_a(salad,300).
food(bagel).
food(sandwich).
food(salad).
% allow any combination of foods to be selected
{ selected(P) } :- food(P).
% sum calories on selected foods
total(S) :- S = #sum{ I : food_a(P,I), selected(P) }.
% limit total calories
:- total(S), S>=500.
#show selected/1.
#show total/1.
哪个产量
> clingo how-to-sum-clingo.asp 0
clingo version 4.5.4
Reading from how-to-sum-clingo.asp
Solving...
Answer: 1
total(0)
Answer: 2
selected(sandwich) total(200)
Answer: 3
selected(bagel) total(245)
Answer: 4
selected(bagel) selected(sandwich) total(445)
Answer: 5
selected(salad) total(300)
SATISFIABLE
Models : 5
Calls : 1
Time : 0.002s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 0.000s
关于answer-set-programming - 如何用 Clingo 求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43163232/
我是一名优秀的程序员,十分优秀!