droolsoptaplannerdrools-planner

In Drools, what does it mean to compare IDs


I understand the basics of writing drools rules now but i can't seem to understand in the examples that i've seen (optaplanner), there are comparisons of IDs. Is this necessary? Why is it there?

// RoomOccupancy: Two lectures in the same room at the same period.
// Any extra lecture in the same period and room counts as one more violation.
rule "roomOccupancy"
    when
        Lecture($leftId : id, period != null, $period : period, room != null, $room : room)
        // $leftLecture has lowest id of the period+room combo
        not Lecture(period == $period, room == $room, id < $leftId)
        // rightLecture has the same period
        Lecture(period == $period, room == $room, id > $leftId, $rightId : id)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -1);
end

From my understanding deleting the line with not Lecture(.. and leaving Lecture(period == $period, room == $room) should do the trick. Is my understanding correct or am I missing some use cases here?


Solution

  • You should understand that a pattern such as

    $a: Lecture()
    $b: Lecture()
    

    with two Lecture facts A an B in the system will produce the following matches and firings:

    $a-A, $b-B   (1)
    $a-B, $b-A   (2)
    $a-A, $b-A
    $a-B, $b-B
    

    Therefore, to reduce the unwanted combinations you need have a way to ascertain to have not identical facts matching (bound to) $a and $b:

    $a: Lecture( $ida: id )
    $b: Lecture( $idb: id != $ida )
    

    However, using not equal still produces combinations (1) and (2).