djb
djb

Reputation: 1674

Drools technique for dealing with subsets?

Let's say I have this list:

id| type   | var     
1 | Type A |  4
2 | Type A |  4
3 | Type A |  4
4 | Type A |  4
5 | Type B |  3
6 | Type B |  3
7 | Type B |  3

I need to change this to:

id| type   | var     
1 | Type A |  7
2 | Type A |  7
3 | Type A |  7
4 | Type A |  7
5 | Type B |  7
6 | Type B |  7
7 | Type B |  7

(I'm adding the third column)

when
    $listA : ArrayList( ) from collect( Thing(type == 'A') )
    $listB : ArrayList( ) from collect( Thing(type == 'B') )
    erm...
then
    um...
end

Anyone have any bright ideas?

Upvotes: 0

Views: 171

Answers (1)

laune
laune

Reputation: 31300

Edited after OP's update

declare SumOfVal
  sum: int
end

rule "computeSum"
when
    not SumOfVal()
    Number( $iv: intValue )
        from accumulate( Thing( $var: var )
                         init( int sum = 0; Set nums = new HashSet(); )
                         action( if( nums.add( $var ) ) sum += $var; )
                         result( sum ) )
then
    insert( new SumOfVal( $iv ) );
end

rule "setSum"
when
    SumOfVal( $sum: sum )
    $t: Thing( var != $sum )
then
    modify( $t ){ setVar( $sum ) }
end

The fact SumOfVal will have to remain in Working Memory to avoid that the same process is iterated over and over again, unless you have a field in Thing that can be used to indicate that this update has been performed.

Upvotes: 1

Related Questions