Skip to main content
Z3 excels at solving constraint satisfaction problems (CSPs) where you need to find values that satisfy a set of constraints. This use case is fundamental to scheduling, resource allocation, planning, and configuration management.

When to Use Constraint Solving

Use Z3 for constraint solving when you have:
  • Scheduling problems: Assign tasks to time slots or resources
  • Planning problems: Find sequences of actions to achieve a goal
  • Configuration problems: Determine valid system configurations
  • Resource allocation: Distribute limited resources optimally
  • Puzzle solving: Sudoku, n-queens, graph coloring, etc.

Core Concepts

Constraint solving in Z3 involves:
  1. Variables: Declare decision variables with appropriate types (Int, Bool, BitVec, etc.)
  2. Domains: Specify the valid range of values for each variable
  3. Constraints: Express relationships between variables
  4. Solver: Check satisfiability and extract solutions

Example: Sudoku Solver

Sudoku is a classic constraint satisfaction problem where you fill a 9×9 grid with digits 1-9 such that each row, column, and 3×3 box contains all digits exactly once.

Example: Scheduling Problem

Schedule tasks with dependencies and resource constraints:

Example: All-Interval Series

The All-Interval Series Problem finds sequences where adjacent differences form a permutation:

Choosing the Right Solver

Z3 provides specialized solvers for different constraint types:
  • Solver(): General-purpose SMT solver
  • SolverFor("QF_FD"): Finite domain solver for Boolean, bit-vector, and bounded integer constraints
  • Optimize(): For optimization problems with objective functions
For pure constraint satisfaction with finite domains, use SolverFor("QF_FD") for better performance.

Optimization Techniques

Breaking Symmetries

Add constraints to eliminate symmetric solutions:

Using Cardinality Constraints

Use AtMost, AtLeast, and PbEq for efficient encoding:

Incremental Solving

Use push/pop for exploring variations:
  • Solvers: Understanding solver APIs
  • Models: Extracting and interpreting solutions
  • Tactics: Solver strategies and preprocessing

Further Examples

See the Z3 repository for more constraint solving examples:
  • examples/python/trafficjam.py: Rush Hour puzzle solver using Datalog
  • examples/python/all_interval_series.py: Complete implementation
  • examples/java/JavaExample.java: Sudoku solver in Java