Description
This is a JavaScript library to solve exact cover problems by implementing Donald E. Knuth's Algorithm X using the Dancing Links technique.
- Knuth's original paper
- Knuth's Algorithm X (Wikipedia)
- Dancing Links (Wikipedia)
- Exact cover (Wikipedia)
Examples
Simple Example
var dlxlib = ; var matrix = 1 0 0 0 0 1 1 0 1 0 0 1 0 0 1 1 0 1 0 0 0 0 1 0; var solutions = dlxlib;for var i = 0; i < solutionslength; i++ console; // solution[0]: [0,3,4]// solution[1]: [1,2]// solution[2]: [2,4,5]
Callbacks
The onSearchStep
callback is particularly useful for visualising the progress of the algorithm.
var dlxlib = ; var matrix = 1 0 0 0 0 1 1 0 1 0 0 1 0 0 1 1 0 1 0 0 0 0 1 0; var searchStepCount = 0; { console;} var solutionCount = 0; { console; searchStepCount = 0;} dlxlib; // partial solution[0]: []// partial solution[1]: [0]// partial solution[2]: [0,3]// partial solution[3]: [0,3,4]// solution[0]: [0,3,4]// partial solution[0]: [2]// partial solution[1]: [2,1]// solution[1]: [2,1]// partial solution[0]: [2,4]// partial solution[1]: [2,4,5]// solution[2]: [2,4,5]
Specifying the number of solutions to return
var dlxlib = ; var matrix = 1 0 0 0 0 1 1 0 1 0 0 1 0 0 1 1 0 1 0 0 0 0 1 0; var solutions = dlxlib;if solutionslength console; // first solution: [0,3,4]
Using the solution generator
As an alternative to dlxlib.solve
, dlxlib.solutionGenerator
returns a
Generator.
; const matrix = 1 0 0 0 0 1 1 0 1 0 0 1 0 0 1 1 0 1 0 0 0 0 1 0; const generator = ;const iteratorResult = generatornext;if !iteratorResultdone console; // first solution: [0,3,4]