简体   繁体   中英

Choco Solver math expression generation

I want to use Choco solver to write a Java program that generates math problems that satisfy a number of constraints. The problems have to take the following form:

x @ y ∆ z = r

Where:

  • x , y & z are positive integers, not necessarily different from one another, with one of them being 2 digits long and the other two 1 digit long

  • @ & are operators +, - or * (note that both can also stand for the same operator)

  • r is a positive 1-digit integer

I want to generate these math problems "on demand" (as in, one at the time) and they need to be randomised (ie there no should be no pattern or fixed order across the generated problems).

It has been well over 10 years since I have done constraint (satisfaction) programming, but I believe C(S)P (preferably by means of Choco), is a suitable tool to apply here. Is this correct and can someone help me get started?

You certainly can model such a problem with a CP solver like choco. You need to have a look at the documentation and tutorials for more details, but you will need :

  • to create a Model ,
  • to declare integer variables ( IntVar ) for x , y and z ,
  • to link them with constraints, I would suggest to use IntVar expression API to ease declaration. Such API allows to build arithmetical, logical and relational expressions like.

Here is a simple example:

Model model = new Model();
IntVar x = model.intVar(0, 9);
IntVar y = model.intVar(0, 9);
IntVar z = model.intVar(0, 9);
int r = 10;
x.add(y).sub(z).eq(r).post(); 
model.getSolver().showSolutions(
    () -> String.format("%d + %d - %d = %d",
            x.getValue(), y.getValue(), z.getValue(), r));
model.getSolver().findAllSolutions();

The way add , sub and mul are combined depends on your random selector. Then, you can try to encode the expression with a table constraints or let the solver choose.

Everything is in the documentation and official tutorials ( http://choco-tuto.readthedocs.io/en/latest/ ). If you feel this is too complex, look at this ultra simple example ( https://www.cosling.com/choco-solver/hello-world ). It shows how to make a+b<8, from that you can do: x@y=AA delta z =r (through arithm and/or times constraint)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM