knapsacker 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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c9762687759b11f1d92bb9a0e54e44ed81850656fe3e4390728cf0fcf58241f9
4
+ data.tar.gz: c22a6b28e5d07062ff5ca2fc62d39fc421e5fb5b8b27cb77582c545cebb6a750
5
+ SHA512:
6
+ metadata.gz: b069dd7a9f8d9048f9a6c13be447d58a8cf8f0d08ab139304a88906a8809dc42e87b0c983cfab14c68a2fa931909880a70e7d4a063f6cfaca79e4ba3e2d2335c
7
+ data.tar.gz: 1cc61dd7367d7806b2b4046562a7f94197ff9cd069a8415d8917faada9b61e0858a227698b8d82ad0264235f317693dde97c06e44cbd0c228089ab3690f1b056
@@ -0,0 +1,11 @@
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
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1 @@
1
+ 2.6.3
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.3
7
+ before_install: gem install bundler -v 2.0.1
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at irohiroki@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in knapsacker.gemspec
4
+ gemspec
@@ -0,0 +1,35 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ knapsacker (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ diff-lcs (1.3)
10
+ rake (10.5.0)
11
+ rspec (3.8.0)
12
+ rspec-core (~> 3.8.0)
13
+ rspec-expectations (~> 3.8.0)
14
+ rspec-mocks (~> 3.8.0)
15
+ rspec-core (3.8.0)
16
+ rspec-support (~> 3.8.0)
17
+ rspec-expectations (3.8.3)
18
+ diff-lcs (>= 1.2.0, < 2.0)
19
+ rspec-support (~> 3.8.0)
20
+ rspec-mocks (3.8.0)
21
+ diff-lcs (>= 1.2.0, < 2.0)
22
+ rspec-support (~> 3.8.0)
23
+ rspec-support (3.8.0)
24
+
25
+ PLATFORMS
26
+ ruby
27
+
28
+ DEPENDENCIES
29
+ bundler (~> 2.0)
30
+ knapsacker!
31
+ rake (~> 10.0)
32
+ rspec (~> 3.0)
33
+
34
+ BUNDLED WITH
35
+ 2.0.1
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Hiroki Yoshioka
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.
@@ -0,0 +1,81 @@
1
+ # Knapsacker
2
+
3
+ Knapsacker is a [Knapsack problem](https://en.wikipedia.org/wiki/Knapsack_problem) solver in Ruby, using branch and bound algorithm.
4
+
5
+ It has a simple API and may solve problems in your holiday programming. (That is, it's not optimized. Yet.)
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'knapsacker'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install knapsacker
22
+
23
+ ## Usage
24
+
25
+ First, instanciate Knapsacker with an array of your items. The items must respond to `value` and `cost`. And a keyword argument `capacity` is mandatory. e.g.:
26
+
27
+ ```ruby
28
+ Item = Struct.new(:value, :cost)
29
+ knapsacker = Knapsacker.new([Item.new(3, 4), Item.new(4, 5)], capacity: 5)
30
+ ```
31
+
32
+ Then call `pack`:
33
+
34
+ ```ruby
35
+ items_to_take = knapsacker.pack
36
+ ```
37
+
38
+ It will return items you should take.
39
+
40
+ ### Similar projects
41
+
42
+ There are some knapsack problem solver in Ruby but none has API. (Some of them accepts items as command line arguments or data in file.)
43
+
44
+ * [danielsellergren/ruby-knapsack](https://github.com/danielsellergren/ruby-knapsack) ... Accepts command line arguments
45
+ * [sucanjan/knapsack-solver](https://github.com/sucanjan/knapsack-solver) ... Accepts data files, Gnuplot-able
46
+ * [soulcutter/no_change_please](https://github.com/soulcutter/no_change_please) ... Accepts a data file
47
+ * [mertbulan/knapsack-problem](https://github.com/mertbulan/knapsack-problem) ... No API
48
+ * [pedroperrone/knapsack-problem](https://github.com/pedroperrone/knapsack-problem) ... No API
49
+ * [shouheiyamauchi/KnapsackProblemSolver](https://github.com/shouheiyamauchi/KnapsackProblemSolver) ... No API
50
+ * [Adacchi3/KnapsackProblem](https://github.com/Adacchi3/KnapsackProblem) ... No API
51
+ * [sas145alex/knapsack_greedy](https://github.com/sas145alex/knapsack_greedy) ... No API
52
+ * [bsmlima/connected-knapsack](https://github.com/bsmlima/connected-knapsack) ... No README
53
+ * [mhartman4/fanduel-scrape](https://github.com/mhartman4/fanduel-scrape) ... No README
54
+
55
+ ### Roadmap
56
+
57
+ * 1.0
58
+ * Interface to support the general form of Knapsack problem, including:
59
+ * Multiple inequality constraints
60
+ * Multiple equality constraints
61
+ * Spport for items that have interface other than `value` and `cost`
62
+ * 1.1
63
+ * Some optimization, maybe. Either in C, either with some smarter algorithm.
64
+
65
+ ## Development
66
+
67
+ 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.
68
+
69
+ To install this gem onto your local machine, run `bundle exec rake install`.
70
+
71
+ ## Contributing
72
+
73
+ Bug reports and pull requests are welcome on GitHub at https://github.com/irohiroki/knapsacker. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
74
+
75
+ ## License
76
+
77
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
78
+
79
+ ## Code of Conduct
80
+
81
+ Everyone interacting in the Knapsacker project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/irohiroki/knapsacker/blob/master/CODE_OF_CONDUCT.md).
@@ -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
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "knapsacker"
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__)
@@ -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,27 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "knapsacker/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "knapsacker"
8
+ spec.version = Knapsacker::VERSION
9
+ spec.authors = ["Hiroki Yoshioka"]
10
+ spec.email = ["irohiroki@gmail.com"]
11
+
12
+ spec.summary = %q{Knapsack problem solver with a simple API}
13
+ spec.description = %q{Knapsacker is a Knapsack (combinatorial opimization) problem solver with Branch and bound algorithm.}
14
+ spec.homepage = "https://github.com/irohiroki/knapsacker"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
18
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 2.0"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "rspec", "~> 3.0"
27
+ end
@@ -0,0 +1,80 @@
1
+ require "set"
2
+
3
+ require "knapsacker/node"
4
+ require "knapsacker/version"
5
+
6
+ class Knapsacker
7
+ def initialize(items, capacity:)
8
+ @items = items.sort {|a, b| b.value.to_f / b.cost <=> a.value.to_f / a.cost } # TODO assert cost
9
+ @capacity = capacity
10
+ @candidates = SortedSet.new
11
+ end
12
+
13
+ def pack
14
+ make_initial_node
15
+
16
+ loop do
17
+ node = select_node_to_grow
18
+ if node
19
+ grow(node, node.item_index + 1)
20
+ else
21
+ return node_with_highest_value.items
22
+ end
23
+ end
24
+ end
25
+
26
+ def grow(node, next_index)
27
+ next_item = @items[next_index]
28
+
29
+ if node.positive_child_growable?
30
+ if next_item && node.cost + next_item.cost <= @capacity
31
+ upper_bound = node.value + next_item.value + upper_bound_beyond(next_index, capacity: @capacity - node.cost - next_item.cost)
32
+ node.positive_child = Node.new(next_index, next_item, upper_bound, node)
33
+ @candidates << node.positive_child
34
+ else
35
+ node.cap_positive_child!
36
+ end
37
+ elsif node.negative_child_growable?
38
+ if next_item
39
+ upper_bound = node.value + upper_bound_beyond(next_index, capacity: @capacity - node.cost)
40
+ node.negative_child = Node.new(next_index, nil, upper_bound, node)
41
+ @candidates << node.negative_child
42
+ @candidates.delete(node)
43
+ else
44
+ node.cap_negative_child!
45
+ end
46
+ end
47
+ end
48
+
49
+ def upper_bound_beyond(prev_index, capacity: capacity)
50
+ index = prev_index + 1
51
+ item = @items[index]
52
+
53
+ return 0 unless item
54
+
55
+ if item.cost > capacity
56
+ item.value.to_f * capacity / item.cost
57
+ else
58
+ item.value + upper_bound_beyond(index, capacity: capacity - item.cost)
59
+ end
60
+ end
61
+
62
+ private
63
+ def make_initial_node
64
+ @candidates << Node.new(-1, nil, upper_bound_beyond(-1, capacity: @capacity), nil)
65
+ end
66
+
67
+ def select_node_to_grow
68
+ hopeful_node = @candidates.first
69
+
70
+ unless hopeful_node.leaf?
71
+ hopeful_node
72
+ end
73
+ end
74
+
75
+ def node_with_highest_value
76
+ @candidates.reduce do |provisional, candidate|
77
+ provisional.value >= candidate.value ? provisional : candidate
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,71 @@
1
+ class Knapsacker
2
+ class Node
3
+ attr_accessor :negative_child
4
+ attr_accessor :positive_child
5
+ attr_reader :item_index
6
+ attr_reader :upper_bound
7
+
8
+ def initialize(item_index, item, upper_bound, parent)
9
+ @item_index = item_index
10
+ @item = item
11
+ @upper_bound = upper_bound
12
+ @parent = parent
13
+ end
14
+
15
+ def <=>(other)
16
+ if other.upper_bound == upper_bound
17
+ other.item_index <=> item_index
18
+ else
19
+ other.upper_bound <=> upper_bound
20
+ end
21
+ end
22
+
23
+ def cap_negative_child!
24
+ @negative_child = :cap
25
+ end
26
+
27
+ def cap_positive_child!
28
+ @positive_child = :cap
29
+ end
30
+
31
+ def cost
32
+ if @parent
33
+ @parent.cost + (@item ? @item.cost : 0)
34
+ else
35
+ 0
36
+ end
37
+ end
38
+
39
+ def items
40
+ if @parent
41
+ if @item
42
+ @parent.items << @item
43
+ else
44
+ @parent.items
45
+ end
46
+ else
47
+ []
48
+ end
49
+ end
50
+
51
+ def leaf?
52
+ @negative_child == :cap && @positive_child == :cap
53
+ end
54
+
55
+ def negative_child_growable?
56
+ @negative_child.nil?
57
+ end
58
+
59
+ def positive_child_growable?
60
+ @positive_child.nil?
61
+ end
62
+
63
+ def value
64
+ if @parent
65
+ @parent.value + (@item ? @item.value : 0)
66
+ else
67
+ 0
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,3 @@
1
+ class Knapsacker
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,102 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: knapsacker
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Hiroki Yoshioka
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-05-06 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: '2.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
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
+ description: Knapsacker is a Knapsack (combinatorial opimization) problem solver with
56
+ Branch and bound algorithm.
57
+ email:
58
+ - irohiroki@gmail.com
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".gitignore"
64
+ - ".rspec"
65
+ - ".ruby-version"
66
+ - ".travis.yml"
67
+ - CODE_OF_CONDUCT.md
68
+ - Gemfile
69
+ - Gemfile.lock
70
+ - LICENSE.txt
71
+ - README.md
72
+ - Rakefile
73
+ - bin/console
74
+ - bin/setup
75
+ - knapsacker.gemspec
76
+ - lib/knapsacker.rb
77
+ - lib/knapsacker/node.rb
78
+ - lib/knapsacker/version.rb
79
+ homepage: https://github.com/irohiroki/knapsacker
80
+ licenses:
81
+ - MIT
82
+ metadata: {}
83
+ post_install_message:
84
+ rdoc_options: []
85
+ require_paths:
86
+ - lib
87
+ required_ruby_version: !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - ">="
90
+ - !ruby/object:Gem::Version
91
+ version: '0'
92
+ required_rubygems_version: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ requirements: []
98
+ rubygems_version: 3.0.3
99
+ signing_key:
100
+ specification_version: 4
101
+ summary: Knapsack problem solver with a simple API
102
+ test_files: []