backtrack-rs 🦀
backtrack
lets you solve backtracking problems
simply and generically.
Problems are defined by their scope and checks against possible solutions.
A Scope determines length and allowed values of a solution.
The domain defaults to usize
, but any T
works if it lives as long as its Scope
, including references.
The Check or CheckInc trait determines whether a particular combination of values is satisfying.
Usage
It is required that solutions shorter than the entire scope, i.e. partial solutions must satisfy if the completed solutions should as well.
Solvers borrow a problem in search for candidate solutions.
Checks
We define the problem of counting down with a limited set of numbers and solve iteratively.
use ;
use IterSolveNaive;
// helper trait to filter solutions of interest
use IterSolveExt;
/// Obtain permutations of some 3 descending numbers
let solver = new;
let mut sats = solver.sat_iter;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Incremental Checks
If your checks can be formulated against a reduced solution, implement CheckInc instead.
The same result as above can be obtained by first computing intermediate values for any given sat check. Such an approach makes sense if work between prior candidate values should be reused.
use ;
use ;
// ...
// since `CheckInc` works from accumulated state, a solver that caches them should be used
let mut sats = new.sat_iter;
// ... gives the same results as above
Examples
Checkout the examples
folder for example problems.
# 4-queens solution
|
## n_queens.rs: NQueens { n: 4 }
## Sat([1, 3, 0, 2])
## Sat([2, 0, 3, 1])
# sequence of numbers which sum up to a minimum value but not more
|
Benchmarks
backtrack-rs
uses criterion for benches.
Todos
- planning / ordered solutions
- parallelize search