exact_matrix_cover 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3c6e7574ad57165ba9c0a705f7b5923c5a5bfb071f3b06e1888832b27029579d
4
+ data.tar.gz: 44afa979f59f6d6d8fd18b4bb922d83cd5d47d3c69436ed9aea037531756930b
5
+ SHA512:
6
+ metadata.gz: 69fa202fdca99e2921014a0bff4f09862adb236fc3c05acfe2a61e97b5931d1e8ab8b742f992ad8b098459b24f5e2aaa9dbc22e87bc6fba103933a860df8d291
7
+ data.tar.gz: 82dcf7d5a84dedda95feab12895aa844b427c7f0b5698d4f335cd751237b243e6226a23d6ad015c8ffe4aaa25b06a1102637bd4174a9aca7359145030b3a0f84
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ .byebug_history
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.5.1
5
+ before_install: gem install bundler -v 1.16.2
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in exact_cover.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,37 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ exact_matrix_cover (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ byebug (11.0.1)
10
+ diff-lcs (1.3)
11
+ rake (10.5.0)
12
+ rspec (3.8.0)
13
+ rspec-core (~> 3.8.0)
14
+ rspec-expectations (~> 3.8.0)
15
+ rspec-mocks (~> 3.8.0)
16
+ rspec-core (3.8.0)
17
+ rspec-support (~> 3.8.0)
18
+ rspec-expectations (3.8.2)
19
+ diff-lcs (>= 1.2.0, < 2.0)
20
+ rspec-support (~> 3.8.0)
21
+ rspec-mocks (3.8.0)
22
+ diff-lcs (>= 1.2.0, < 2.0)
23
+ rspec-support (~> 3.8.0)
24
+ rspec-support (3.8.0)
25
+
26
+ PLATFORMS
27
+ ruby
28
+
29
+ DEPENDENCIES
30
+ bundler (~> 1.16)
31
+ byebug
32
+ exact_matrix_cover!
33
+ rake (~> 10.0)
34
+ rspec (~> 3.0)
35
+
36
+ BUNDLED WITH
37
+ 1.17.2
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Jerome Marhic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,80 @@
1
+ # ExactCover
2
+
3
+ This gem is a ruby implementation of D.Knuth's paper "Dancing Link" : https://arxiv.org/abs/cs/0011047
4
+ It implements a solver for the "exact cover of a matrix" problem. For a given matrix of 0s and 1s, it finds a set of
5
+ rows that contains exactly one "1" in each column.
6
+ This can be used to implement a tetramino or a sudoku solver.
7
+
8
+ ## Installation
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem 'exact_cover'
14
+ ```
15
+
16
+ And then execute:
17
+
18
+ $ bundle
19
+
20
+ Or install it yourself as:
21
+
22
+ $ gem install exact_cover
23
+
24
+ ## Usage
25
+
26
+ Basic usage
27
+ ```
28
+ require "exact_cover"
29
+
30
+ matrix =
31
+ [
32
+ [0, 0, 1, 0, 1, 1, 0],
33
+ [1, 0, 0, 1, 0, 0, 1],
34
+ [0, 1, 1, 0, 0, 1, 0],
35
+ [1, 0, 0, 1, 0, 0, 0],
36
+ [0, 1, 0, 0, 0, 0, 1],
37
+ [0, 0, 0, 1, 1, 0, 1]
38
+ ]
39
+
40
+ solutions = ExactCover::CoverSolver.new(matrix).call
41
+ solutions.count
42
+ # => 1
43
+ solutions.first
44
+ # => [[1, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0, 1], [0, 0, 1, 0, 1, 1, 0]]
45
+ # this corresponds to the 4th, 3rd and first rows of the given matrix
46
+ ```
47
+
48
+ You can iterate through all the solutions
49
+ ```
50
+ require "exact_cover"
51
+
52
+ matrix =
53
+ [
54
+ [1, 1],
55
+ [0, 1],
56
+ [1, 0]
57
+ ]
58
+
59
+ solutions = ExactCover::CoverSolver.new(matrix).call
60
+ solutions.count
61
+ # => 2
62
+ solutions.next
63
+ # => [[1, 1]]
64
+ solutions.next
65
+ # => [[1, 0], [0, 1]]
66
+ ```
67
+
68
+ ## Development
69
+
70
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
71
+
72
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
73
+
74
+ ## Contributing
75
+
76
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/exact_cover.
77
+
78
+ ## License
79
+
80
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "exact_cover"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,39 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "exact_cover/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "exact_matrix_cover"
8
+ spec.version = ExactCover::VERSION
9
+ spec.authors = ["Jerome Marhic"]
10
+ spec.email = ["jerome.marhic@effilab.com"]
11
+
12
+ spec.summary = "Find the set of rows that correspond to an exact cover for a given matrix."
13
+ spec.description = "Implementation of D.Knuth 'dancing links' algorithm to solve the exact cover problem."
14
+ spec.homepage = "https://github.com/MarhicJeromeGIT/exact_cover"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata["allowed_push_host"] = "https://rubygems.org/"
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against " \
23
+ "public gem pushes."
24
+ end
25
+
26
+ # Specify which files should be added to the gem when it is released.
27
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
28
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
29
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ spec.add_development_dependency "bundler", "~> 1.16"
36
+ spec.add_development_dependency "rake", "~> 10.0"
37
+ spec.add_development_dependency "rspec", "~> 3.0"
38
+ spec.add_development_dependency "byebug"
39
+ end
File without changes
@@ -0,0 +1,8 @@
1
+ require "exact_cover/version"
2
+ require "exact_cover/cover_solver"
3
+ require "exact_cover/matrix_preprocessor"
4
+ require "exact_cover/data_object"
5
+ require "exact_cover/column_object"
6
+
7
+ module ExactCover
8
+ end
@@ -0,0 +1,14 @@
1
+ module ExactCover
2
+ # a column header
3
+ class ColumnObject < DataObject
4
+ attr_accessor :size # size (number of 1 in the column)
5
+ attr_reader :name # name
6
+
7
+ def initialize(size, name)
8
+ super(nil)
9
+
10
+ @size = size
11
+ @name = name
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,165 @@
1
+ # Cover problem solver
2
+ # Ruby implementation of https://arxiv.org/abs/cs/0011047 (Dancing Link algorithm)
3
+ # Can be used to solve tetramino or sudoku problems
4
+ # @author Marhic Jerome 2019
5
+
6
+ module ExactCover
7
+ # Solves the cover problem with algorithm "X"
8
+ class CoverSolver
9
+ class InvalidMatrixSize < StandardError; end
10
+
11
+ attr_reader :matrix
12
+ attr_reader :column_count
13
+
14
+ def initialize(matrix)
15
+ @matrix = matrix
16
+ # sanity check
17
+ if !matrix.is_a?(Array) || matrix.size == 0 || matrix[0].size == 0
18
+ raise(InvalidMatrixSize, "non-empty 2-dimensional array expected, got #{matrix.inspect}")
19
+ end
20
+
21
+ @column_count = matrix[0].size
22
+ end
23
+
24
+ # Solve the exact cover problem for the given matrix
25
+ # @return [Enumerator] An enumeration of the all the possible solutions
26
+ def call
27
+ root = MatrixPreprocessor.new(matrix).call
28
+ Enumerator.new do |y|
29
+ search(0, root, y)
30
+ end
31
+ end
32
+
33
+ private
34
+
35
+ # @param k [Integer] solution "deepness"
36
+ # @param root [ColumnObject] root
37
+ # @param y [Yielder] enumerator yielder
38
+ # @param solution [Array<DataObject>] current solution
39
+ def search(k, root, y, solution = [])
40
+ if root.right == root
41
+ y.yield format_solution(solution)
42
+ return
43
+ end
44
+
45
+ column = choose_column(root)
46
+ cover_column(column)
47
+
48
+ r = column.down
49
+ loop do
50
+ break if r == column
51
+
52
+ solution[k] = r
53
+
54
+ j = r.right
55
+ loop do
56
+ break if j == r
57
+
58
+ cover_column(j.column)
59
+ j = j.right
60
+ end
61
+
62
+ search(k + 1, root, y, solution.dup)
63
+
64
+ j = r.left
65
+ loop do
66
+ break if j == r
67
+
68
+ uncover_column(j.column)
69
+
70
+ j = j.left
71
+ end
72
+
73
+ r = r.down
74
+ end
75
+
76
+ uncover_column(column)
77
+ end
78
+
79
+ # @solution consists in an array of DataObject,
80
+ # formats it to an array of 0 and 1 rows (corresponding to some rows of the given matrix)
81
+ # @return [Array<Array>] Subset of the matrix rows corresponding to an exact cover
82
+ def format_solution(solution)
83
+ rows = []
84
+ solution.each do |data_object|
85
+ row = Array.new(column_count, 0)
86
+ current = data_object
87
+ loop do
88
+ row[current.column.name.to_i] = 1
89
+ current = current.right
90
+ break if current == data_object
91
+ end
92
+ rows << row
93
+ end
94
+ rows
95
+ end
96
+
97
+ def choose_column(root)
98
+ # Minimize the branching factor by choosing the column with the lowest size
99
+ min_size = root.right.size
100
+ min_size_column = root.right
101
+
102
+ current_column = min_size_column.right
103
+ loop do
104
+ break if current_column == root
105
+
106
+ if current_column.size < min_size
107
+ min_size = current_column.size
108
+ min_size_column = current_column
109
+ end
110
+
111
+ current_column = current_column.right
112
+ end
113
+
114
+ min_size_column
115
+ end
116
+
117
+ # removes c from the header list
118
+ # @param column [ColumnObject]
119
+ def cover_column(column)
120
+ column.right.left = column.left
121
+ column.left.right = column.right
122
+
123
+ i = column.down
124
+ loop do
125
+ break if i == column
126
+
127
+ j = i.right
128
+ loop do
129
+ break if j == i
130
+
131
+ j.down.up = j.up
132
+ j.up.down = j.down
133
+ j.column.size -= 1
134
+
135
+ j = j.right
136
+ end
137
+
138
+ i = i.down
139
+ end
140
+ end
141
+
142
+ def uncover_column(column)
143
+ i = column.up
144
+ loop do
145
+ break if i == column
146
+
147
+ j = i.left
148
+ loop do
149
+ break if j == i
150
+
151
+ j.column.size += 1
152
+ j.down.up = j
153
+ j.up.down = j
154
+
155
+ j = j.left
156
+ end
157
+
158
+ i = i.up
159
+ end
160
+
161
+ column.left.right = column
162
+ column.right.left = column
163
+ end
164
+ end
165
+ end
@@ -0,0 +1,16 @@
1
+ module ExactCover
2
+ # represents a "1" in the given matrix
3
+ class DataObject
4
+ attr_accessor :left, :right, :up, :down # left, right, up and down links
5
+ attr_reader :column # link to column object
6
+
7
+ # @param column [ColumnObject]
8
+ def initialize(column)
9
+ @column = column
10
+ @left = nil
11
+ @right = nil
12
+ @up = nil
13
+ @down = nil
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,96 @@
1
+ module ExactCover
2
+ # Transforms an array into a linked list of data and column objects
3
+ class MatrixPreprocessor
4
+ attr_reader :matrix
5
+ attr_reader :row_count
6
+ attr_reader :col_count
7
+
8
+ def initialize(matrix)
9
+ @matrix = matrix
10
+ @row_count = matrix.size
11
+ @col_count = matrix[0].size
12
+ end
13
+
14
+ def call
15
+ # Generates the column objects
16
+ headers = []
17
+ (0..col_count - 1).each do |col|
18
+ col_size = size(col)
19
+ headers[col] = ColumnObject.new(col_size, col.to_s)
20
+ end
21
+
22
+ # Fill the left and right for each header object
23
+ prev = headers[-1]
24
+ headers.each do |current|
25
+ current.left = prev
26
+ prev.right = current
27
+ prev = current
28
+ end
29
+
30
+ # Generates the data objects (one for each 1 in the matrix)
31
+ data_objects = []
32
+ row_objects_array = []
33
+ col_objects_array = []
34
+ (0..row_count - 1).each do |row|
35
+ data_objects[row] = []
36
+ row_objects_array[row] = []
37
+ (0..col_count - 1).each do |col|
38
+ column = headers[col]
39
+ col_objects_array[col] = [column] if col_objects_array[col].nil?
40
+ next unless matrix[row][col] == 1
41
+
42
+ data_object = DataObject.new(column)
43
+ data_objects[row][col] = data_object
44
+ row_objects_array[row] << data_object
45
+ col_objects_array[col] << data_object
46
+ end
47
+ end
48
+
49
+ # Fill the left and right fields
50
+ row_objects_array.each do |row_objects|
51
+ prev = row_objects[-1]
52
+ loop do
53
+ break if row_objects.empty?
54
+
55
+ current = row_objects.shift
56
+ current.left = prev
57
+ prev.right = current
58
+ prev = current
59
+ end
60
+ end
61
+
62
+ # Fill the up and down fields
63
+ col_objects_array.each do |col_objects|
64
+ prev = col_objects[-1]
65
+ loop do
66
+ break if col_objects.empty?
67
+
68
+ current = col_objects.shift
69
+ current.up = prev
70
+ prev.down = current
71
+ prev = current
72
+ end
73
+ end
74
+
75
+ # insert the root between headers[-1] and headers[0]
76
+ root = ColumnObject.new(0, "root")
77
+ headers[-1].right = root
78
+ headers[0].left = root
79
+ root.right = headers[0]
80
+ root.left = headers[-1]
81
+
82
+ root
83
+ end
84
+
85
+ private
86
+
87
+ # @return [Integer] Number of 1 in the given column
88
+ def size(col)
89
+ size = 0
90
+ (0..row_count - 1).each do |row|
91
+ size += 1 if matrix[row][col] == 1
92
+ end
93
+ size
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,3 @@
1
+ module ExactCover
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,119 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: exact_matrix_cover
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jerome Marhic
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-09-26 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: byebug
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description: Implementation of D.Knuth 'dancing links' algorithm to solve the exact
70
+ cover problem.
71
+ email:
72
+ - jerome.marhic@effilab.com
73
+ executables: []
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - ".gitignore"
78
+ - ".rspec"
79
+ - ".travis.yml"
80
+ - Gemfile
81
+ - Gemfile.lock
82
+ - LICENSE.txt
83
+ - README.md
84
+ - Rakefile
85
+ - bin/console
86
+ - bin/setup
87
+ - exact_cover.gemspec
88
+ - examples/sudoku.rb
89
+ - lib/exact_cover.rb
90
+ - lib/exact_cover/column_object.rb
91
+ - lib/exact_cover/cover_solver.rb
92
+ - lib/exact_cover/data_object.rb
93
+ - lib/exact_cover/matrix_preprocessor.rb
94
+ - lib/exact_cover/version.rb
95
+ homepage: https://github.com/MarhicJeromeGIT/exact_cover
96
+ licenses:
97
+ - MIT
98
+ metadata:
99
+ allowed_push_host: https://rubygems.org/
100
+ post_install_message:
101
+ rdoc_options: []
102
+ require_paths:
103
+ - lib
104
+ required_ruby_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: '0'
109
+ required_rubygems_version: !ruby/object:Gem::Requirement
110
+ requirements:
111
+ - - ">="
112
+ - !ruby/object:Gem::Version
113
+ version: '0'
114
+ requirements: []
115
+ rubygems_version: 3.0.3
116
+ signing_key:
117
+ specification_version: 4
118
+ summary: Find the set of rows that correspond to an exact cover for a given matrix.
119
+ test_files: []