【问题标题】:Optaplanner - Drools for int array constraintOptaplanner - 用于 int 数组约束的 Drools
【发布时间】:2021-06-09 06:19:03
【问题描述】:

我正在尝试编写一个约束来检查整数数组 (binUsedArray) 的任何元素是否大于界限 (dailyMaxNb)。

rule "BinResourceConstraint"
    when
        BinResource($array : binUsedArray, $dailyMaxNb : dailyMaxNb)
        $x : Integer() from $array
        $x > $dailyMaxNb
    then
        scoreHolder.addHardConstraintMatch(kcontext, -1);
end

我阅读了 drools doc 5.1.8 并尝试编写类似这样的规则

rule "Iterate the numbers"
when
    $xs : List()
    $x : Integer() from $xs
then
    $x matches and binds to each Integer in the collection
end

但出现了一些错误:

Caused by: java.lang.RuntimeException: [Message [id=1, kieBase=defaultKieBase, level=ERROR, path=com/cttq/aps/solver/taskScheduleConstraint.drl, line=78, column=0
   text=[ERR 102] Line 78:11 mismatched input '>' in rule "BinResourceConstraint"], Message [id=2, kieBase=defaultKieBase, level=ERROR, path=com/cttq/aps/solver/taskScheduleConstraint.drl, line=0, column=0
   text=Parser returned a null Package]]

===== 更新了 BinResource 类,binUsedArray 是一个大小为 30 的 int 数组,用于保留接下来 30 天使用的 bin 数量。

@PlanningEntity
public class BinResource {
    private String index;
    private String binType;
    private String binArea;

    private int dailyMaxNb;

    @CustomShadowVariable(variableListenerRef = @PlanningVariableReference(entityClass = TaskAssignment.class, variableName = "modifiedProcessTimeInShift"))
    private int[] binUsedArray;

【问题讨论】:

  • 澄清一下 -- binUsedArrayint[]Integer[] 并且您想查看该数组中是否有任何值是 > $dailyMaxNb
  • 第二条规则适用于集合。数组不是 java.util.Collection,因此您不能对 int[]/Integer[] 使用相同的工作流程是有道理的。
  • @RoddyoftheFrozenPeas binUsedArray 是 int[] 是的,我想检查这个数组中的每个值。

标签: drools optaplanner


【解决方案1】:

简单的解决方案是将您的数组转换为列表,然后它就可以工作了。 Arrays.asList( array ) 可以在 LHS 上调用以转换数组...类似于:

BinResource($array : binUsedArray, $dailyMaxNb : dailyMaxNb)
$binUsed: List() from Arrays.asList($array)

然后您可以从第二条规则中执行相同的逻辑来找到符合您条件的值:

$x : Integer(this > $dailyMaxNb) from $binUsed

这样,您的规则将为数组/列表中大于 dailyMaxNb 值的每个值 ($x) 触发一次。

rule "BinResourceConstraint"
when
  BinResource($array : binUsedArray, $dailyMaxNb : dailyMaxNb)
  $binUsed: List() from Arrays.asList($array)
  $x : Integer(this > $dailyMaxNb) from $binUsed
then
  // this will trigger once PER MATCH ... 
  // eg if there are 3 values that > dailyMaxNb, this will trigger 3 times
  scoreHolder.addHardConstraintMatch(kcontext, -1);
end

但是,如果您的 binUsedArray 实际上是 ArrayList,则可以省略转换而只使用 $x: Integer(this > $dailyMaxNb) from $array。我提到这一点是因为有时当人们询问“数组”时,他们实际上指的是数组列表,而您没有提供 BinResource 类的代码。话虽如此,您可以将此模式 (MyType( <condition> ) from $collection) 用于任何可迭代集合,以尝试匹配该集合中的所有值。

【讨论】:

  • 非常感谢您快速详细的回放。我将尝试转换为列表数组。我还尝试在帮助类中编写一个自定义函数,它似乎有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多