Documentation
¶
Overview ¶
Package dlx implements Knuth's algorithm DLX (algorithm X implemented in terms of dancing links), which solves exact cover problems.
An exact cover problem is a matrix of 0s and 1s. A solution is a subset of its rows that contains exactly one 1 in each column. Many puzzles and combinatorial problems reduce to this form: see the sudoku solver in the examples/sudoku directory.
Knuth's paper explains the algorithm: https://arxiv.org/abs/cs/0011047
Usage ¶
Consider the exact cover problem specified by the matrix:
1 0 0 1 0 0 1 1 0 0 1 0 0 0 0 0 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 0 1 1 0 1 0 0 0 0 1
The following code finds all solutions to the exact cover problem:
m := dlx.NewMatrix(7)
m.AddRow(0, 3, 6)
m.AddRow(0, 3)
m.AddRow(3, 4, 6)
m.AddRow(2, 4, 5)
m.AddRow(1, 2, 5, 6)
m.AddRow(1, 6)
m.Solve(dlx.SolutionAccepterFunc(func(exactCover [][]int) bool {
fmt.Println("Solution found:")
for _, row := range exactCover {
fmt.Println(row)
}
return false
}))
The code output:
Solution found: [0 3] [2 4 5] [1 6]
Contract ¶
Return true from the accepter to stop the search early. A Matrix stays valid after Solve returns, however the search ended, so it can be solved again and more rows can be added to it.
Invalid arguments are programmer errors and panic with a message prefixed "dlx:". This applies to a negative column count, a column index that is out of range or repeated within a row, and a nil SolutionAccepter interface value. A nil SolutionAccepterFunc is not detected: it panics with a runtime error when the first solution is reported. A rejected row leaves the matrix unchanged.
A Matrix is not safe for concurrent use, and an accepter must not call AddRow or Solve on the matrix being solved. See the Matrix and SolutionAccepter documentation for the details.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Matrix ¶
type Matrix interface {
// AddRow adds a row to the matrix. constraintsRow lists the zero-based
// column indices of the row's 1s, in any order. The slice is not retained.
//
// A row with no indices is ignored: it could not cover anything. Rows have
// no identity, so a row added twice is two rows and yields separate
// solutions.
//
// AddRow panics if an index is outside [0, nColumns) or appears twice in
// constraintsRow. The matrix is unchanged after such a panic.
AddRow(constraintsRow ...int)
// Solve searches for every subset of rows that has exactly one 1 in each
// column, and passes each one to accepter. The search ends when accepter
// returns true or when no solutions remain.
//
// A matrix with no columns has exactly one solution, which is empty. A
// matrix with a column that no row covers has none.
//
// The order of the search is deterministic: matrices built by the same
// sequence of AddRow calls report the same solutions in the same order.
// It branches on the leftmost column with the fewest remaining rows, trying
// that column's rows in AddRow order.
//
// Solve restores the matrix before returning, even after accepter stops the
// search, so it can be called again and more rows can be added. Recursion
// depth is bounded by the number of columns.
//
// Solve panics with a "dlx:" message if accepter is a nil interface value.
// A nil SolutionAccepterFunc is not detected: it panics with a runtime error
// when the first solution is reported, like any panicking accepter.
Solve(accepter SolutionAccepter)
}
Matrix represents an exact cover problem: a matrix of 0s and 1s, for which Solve looks for a subset of rows with exactly one 1 in every column.
A Matrix is not safe for concurrent use, including concurrent calls to Solve.
func NewMatrix ¶
NewMatrix creates the Matrix with the given number of columns. It panics with a "dlx:" message if nColumns is negative. An extremely large nColumns fails with a runtime allocation panic instead.
Example ¶
package main
import (
"fmt"
"github.com/dimchansky/dlx"
)
func main() {
m := dlx.NewMatrix(7)
m.AddRow(0, 3, 6)
m.AddRow(0, 3)
m.AddRow(3, 4, 6)
m.AddRow(2, 4, 5)
m.AddRow(1, 2, 5, 6)
m.AddRow(1, 6)
m.Solve(dlx.SolutionAccepterFunc(func(exactCover [][]int) bool {
fmt.Println("Solution found:")
for _, row := range exactCover {
fmt.Println(row)
}
return false
}))
}
Output: Solution found: [0 3] [2 4 5] [1 6]
type SolutionAccepter ¶
type SolutionAccepter interface {
// AcceptSolution receives one solution and returns true to stop the search.
//
// exactCover holds one element per selected row, each listing the row's
// column indices in the order they were passed to AddRow. The rows appear
// in the order the search selected them, not in AddRow order. Both levels
// of the slice are freshly allocated, so it is safe to retain and modify.
//
// AcceptSolution must not call AddRow or Solve on the matrix being solved.
// If it panics, the matrix is left in an undefined state and must be
// discarded.
AcceptSolution(exactCover [][]int) bool
}
SolutionAccepter receives the solutions of an exact cover problem.
type SolutionAccepterFunc ¶
The SolutionAccepterFunc type is an adapter to allow the use of ordinary functions as SolutionAccepter. If f is a function with the appropriate signature, SolutionAccepterFunc(f) is a SolutionAccepter that calls f.
func (SolutionAccepterFunc) AcceptSolution ¶
func (f SolutionAccepterFunc) AcceptSolution(exactCover [][]int) bool
AcceptSolution calls f(exactCover) and returns its result.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
bells
command
Command bells searches for extents of change ringing on 3 or 4 bells, and prints them to standard output.
|
Command bells searches for extents of change ringing on 3 or 4 bells, and prints them to standard output. |
|
cardtrick
command
Command cardtrick finds a strategy for the five-card trick of Fitch Cheney in its general form, using exact cover.
|
Command cardtrick finds a strategy for the five-card trick of Fitch Cheney in its general form, using exact cover. |
|
coveringsystems
command
Command coveringsystems splits the integers into remainder classes, such as the even numbers, the numbers that leave 1 when divided by 4, and the numbers that leave 3, so that every integer lands in exactly one class.
|
Command coveringsystems splits the integers into remainder classes, such as the even numbers, the numbers that leave 1 when divided by 4, and the numbers that leave 3, so that every integer lands in exactly one class. |
|
crew
command
Command crew reads the flights of a day and a list of candidate crew pairings with their costs from standard input.
|
Command crew reads the flights of a day and a list of candidate crew pairings with their costs from standard input. |
|
fullerene
command
Command fullerene finds the double bonds of a carbon molecule, by default the football-shaped C60, and prints them to standard output.
|
Command fullerene finds the double bonds of a carbon molecule, by default the football-shaped C60, and prints them to standard output. |
|
hamming
command
Command hamming finds perfect codes and uses one to play the seven prisoners hat game.
|
Command hamming finds perfect codes and uses one to play the seven prisoners hat game. |
|
hat
command
Command hat tries to cover a disk with copies of the hat, the aperiodic monotile found in 2023, and prints what it finds to standard output.
|
Command hat tries to cover a disk with copies of the hat, the aperiodic monotile found in 2023, and prints what it finds to standard output. |
|
instrselect
command
Command instrselect picks machine instructions for an arithmetic expression, the way the instruction selection step of a compiler does.
|
Command instrselect picks machine instructions for an arithmetic expression, the way the instruction selection step of a compiler does. |
|
kochenspecker
command
Command kochenspecker tries to colour a set of rays green and red under the rules of the Kochen-Specker theorem: exactly one green ray in every group of mutually perpendicular rays that fills all directions, and at most one green ray in every other perpendicular pair.
|
Command kochenspecker tries to colour a set of rays green and red under the rules of the Kochen-Specker theorem: exactly one green ray in every group of mutually perpendicular rays that fills all directions, and at most one green ray in every other perpendicular pair. |
|
langford
command
Command langford arranges two copies of each number from 1 to n in a row, so that the copies of a number k have exactly k numbers between them, and prints the arrangements to standard output.
|
Command langford arranges two copies of each number from 1 to n in a row, so that the copies of a number k have exactly k numbers between them, and prints the arrangements to standard output. |
|
pentomino
command
Command pentomino tiles a rectangle of 60 cells with the 12 pentominoes, each used exactly once, and prints the tilings to standard output.
|
Command pentomino tiles a rectangle of 60 cells with the 12 pentominoes, each used exactly once, and prints the tilings to standard output. |
|
perfecthash
command
Command perfecthash builds a minimal perfect hash for a list of lowercase words: a table with exactly one slot per word, and a small sum that sends each word to its own slot.
|
Command perfecthash builds a minimal perfect hash for a list of lowercase words: a table with exactly one slot per word, and a small sum that sends each word to its own slot. |
|
queens
command
Command queens places n queens on an n by n chessboard so that no two attack each other, and prints the solutions to standard output.
|
Command queens places n queens on an n by n chessboard so that no two attack each other, and prints the solutions to standard output. |
|
sudoku
command
Command sudoku solves the Sudoku board read from standard input and prints its solutions to standard output.
|
Command sudoku solves the Sudoku board read from standard input and prints its solutions to standard output. |
|
sudoku/parser
Package parser reads Sudoku boards in the text format of the sudoku example.
|
Package parser reads Sudoku boards in the text format of the sudoku example. |
|
sudoku/solver
Package solver solves Sudoku boards by reducing them to exact cover problems for package dlx.
|
Package solver solves Sudoku boards by reducing them to exact cover problems for package dlx. |
|
twelvetone
command
Command twelvetone finds all-interval series: orderings of the n pitches on a circle in which the n-1 steps between neighbours make every interval from 1 to n-1 exactly once.
|
Command twelvetone finds all-interval series: orderings of the n pitches on a circle in which the n-1 steps between neighbours make every interval from 1 to n-1 exactly once. |
|
vuza
command
Command vuza finds the rhythmic canons of a given rhythm: the beats on which copies of the rhythm must enter so that together they strike every beat of a loop exactly once.
|
Command vuza finds the rhythmic canons of a given rhythm: the beats on which copies of the rhythm must enter so that together they strike every beat of a loop exactly once. |
|
witt
command
Command witt searches for Steiner systems: groups of k points, chosen from v points, so that every set of t points lies in exactly one group.
|
Command witt searches for Steiner systems: groups of k points, chosen from v points, so that every set of t points lies in exactly one group. |