我有以下数据集:
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个的组合。任何人都可以建议我必须遵循的变化或步骤才能实现同样的目标。
答案 0 :(得分:2)
您目前正在分别为每种食物做总计。如果您有相同食物的多个值,例如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