Problem Description:
1, Xiao Ming Hand has 50 yuan money;
2, 1 yuan money can buy a bottle of drink;
3, 2 empty bottles can be exchanged for a bottle of drink;
4. The question is: how many bottles of drink can Xiao Ming drink at last?
First, create a new MAVEN project and join the drools dependency
<dependency><groupId>org.drools</groupId><artifactId>drools-core</artifactId> <version>6.2.0.final</version></dependency><dependency><groupid>org.drools</ groupid><artifactid>drools-compiler</artifactid><version>6.2.0.final</version></ Dependency>
Package Com.lala.bean;public class Drinks {private integer money;private integer total = 0;//drink quantity private integer bottle = 0; Number of empty bottles public drinks (Integer money) {This.money = money;} Public Integer Getmoney () {return money;} public void Setmoney ("Integer money") {This.money = money;} Public Integer Gettotal () {return total;} public void Settotal (Integer total) {this.total = total;} Public Integer Getbottle () {return bottle;} public void Setbottle (Integer bottle) {this.bottle = bottle;}}
Drools Rules:
Package Com.drink;import com.lala.bean.drinks;rule ' Money ' salience 2 when $d:D rinks (Money > 0); Then Modify ($d) { Setmoney ($d. Getmoney ()-1),//buy a bottle of settotal ($d. Gettotal () + 1),//drink a bottle of Setbottle ($ D.getbottle () + 1);//Add an empty bottle (add an empty bottle for each bottle) };endrule "Bottle" Salience 1 when $d:D rinks (bottle >= 2); Then Modify ($d) { setbottle ($d. Getbottle ()-2),//2 empty bottles for a bottle of settotal ($d. Gettotal () + 1),//Drink a bottle Setbottle ($d. Getbottle () + 1);//Add an empty bottle (add an empty bottle for each bottle) };end
Test:
Package Com.lala.mydrools;import Org.kie.api.kieservices;import Org.kie.api.runtime.kiecontainer;import Org.kie.api.runtime.kiesession;import Com.lala.bean.drinks;public class Test {static Kiesession getsession () { kieservices ks = KieServices.Factory.get (); Kiecontainer KC = Ks.getkieclasspathcontainer (); Return kc.newkiesession ("Simpleruleksession"); } public static void Main (string[] args) { Kiesession ks = GetSession (); Drinks dr = new Drinks (a); Ks.insert (DR); int count = Ks.fireallrules (); SYSTEM.OUT.PRINTLN ("Always executed" +count+ "rule"); System.out.println ("Can drink in total:" + dr.gettotal () + "bottle"); Ks.dispose (); }}
Finally, the output is:
There are 99 rules that have been executed.
Total Drink: 99 Bottles
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Using drools to solve the problem of Xiao Ming drinking soda