weighted_rand 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 71de44bbe1d43a6dd9572876ac332ae8dc24e95a73ef0fb11018ce2512d0584d
4
+ data.tar.gz: 6598a0ca6c7b566fb55f7bec0ecaea634ef6f62431e01eb60489ed438bd3b11c
5
+ SHA512:
6
+ metadata.gz: 3f91c4e14748243c36feb732d57859ac12fe060f5ad961d4d46cef8bbac914a9c52d5f4aef11e6761031016274d0ab1eec2fbeac28c33f73d5d599d7cd9c983c
7
+ data.tar.gz: c905d8936436b03db171bf467d2e1d2d31f03240ad178bf1b01fe456f311f9dd75935298ccbee42a4b17aad7fc40ad47d2ab30b57067ed217ceb87858af3e55c
data/.rubocop.yml ADDED
@@ -0,0 +1,20 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.7
3
+ DisabledByDefault: true
4
+ Exclude:
5
+ - "gems/**/*"
6
+ NewCops: enable
7
+
8
+ Bundler:
9
+ Enabled: true
10
+
11
+ Gemspec:
12
+ Enabled: true
13
+
14
+ Lint:
15
+ Enabled: true
16
+
17
+ Style/TrailingCommaInArguments:
18
+ EnforcedStyleForMultiline: consistent_comma
19
+ Style/StringLiterals:
20
+ EnforcedStyle: single_quotes
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.1.2
@@ -0,0 +1,11 @@
1
+ {
2
+ "ruby.useLanguageServer": true,
3
+ "ruby.useBundler": true,
4
+ "ruby.format": "rubocop",
5
+ "ruby.lint": {
6
+ "rubocop": true
7
+ },
8
+ "[ruby]": {
9
+ "editor.formatOnSave": true
10
+ }
11
+ }
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Released]
2
+
3
+ ## [0.1.0] - 2023-01-18
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at yuhei.nakasaka@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in weighted_rand.gemspec
6
+ gemspec
7
+
8
+ gem 'minitest', '~> 5.0'
9
+ gem 'rake', '~> 13.0'
data/Gemfile.lock ADDED
@@ -0,0 +1,21 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ weighted_rand (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ minitest (5.17.0)
10
+ rake (13.0.6)
11
+
12
+ PLATFORMS
13
+ x86_64-darwin-20
14
+
15
+ DEPENDENCIES
16
+ minitest (~> 5.0)
17
+ rake (~> 13.0)
18
+ weighted_rand!
19
+
20
+ BUNDLED WITH
21
+ 2.3.7
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 YuheiNakasaka
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,92 @@
1
+ # WeightedRand
2
+
3
+ This gem provides a method to select a element by weighted randomization from a hash with weights.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'weighted_rand'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install weighted_rand
20
+
21
+ ## Usage
22
+
23
+ - Prepare for weights with hash formats.
24
+ - Initialize class and pass the weights to `#new` args.
25
+ - Call `#sample`.
26
+
27
+ ### Linear
28
+
29
+ ```
30
+ weights = {'a' => 1, 'b' => 2, 'c' => 3}
31
+ weighted_rand = WeightedRand::Linear.new(weights)
32
+ weighted_rand.sample #=> c > b > a
33
+ ```
34
+
35
+ ### BinarySearch
36
+
37
+ ```
38
+ weights = {'a' => 1, 'b' => 2, 'c' => 3}
39
+ weighted_rand = WeightedRand::BinarySearch.new(weights)
40
+ weighted_rand.sample #=> c > b > a
41
+ ```
42
+
43
+ ### Walker's Alias
44
+
45
+ - [Alias method](https://en.wikipedia.org/wiki/Alias_method)
46
+
47
+ ```
48
+ weights = {'a' => 1, 'b' => 2, 'c' => 3}
49
+ weighted_rand = WeightedRand::WalkerAlias.new(weights)
50
+ weighted_rand.sample #=> c > b > a
51
+ ```
52
+
53
+ ## Performance
54
+
55
+ - Comparison of Linear/BinarySearch/WalkerAlias/[WeightedRandomizer](https://github.com/ryanlecompte/weighted_randomizer)
56
+ - weights size: 10,000
57
+
58
+ | Repeat | Linear | BinarySearch | WalkerAlias | WeightedRandomizer |
59
+ | ------- | ------: | -----------: | ----------: | -----------------: |
60
+ | 1 | 0.0014s | 0.0013s | 0.0037s | 0.0032s |
61
+ | 10 | 0.0043s | 0.0014s | 0.0038s | 0.0052s |
62
+ | 100 | 0.0299s | 0.0016s | 0.0043s | 0.0369s |
63
+ | 1,000 | 0.3192s | 0.0043s | 0.0054s | 0.3408s |
64
+ | 10,000 | 3.0431s | 0.0189s | 0.0124s | 3.4284s |
65
+ | 100,000 | 30.356s | 0.1575s | 0.0751s | 34.844s |
66
+
67
+ ## Development
68
+
69
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also r
70
+ un `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
+ ## Release
75
+
76
+ ```
77
+ bundle exec rake build
78
+ git push origin <branch>
79
+ bundle exec rake release
80
+ ```
81
+
82
+ ## Contributing
83
+
84
+ Bug reports and pull requests are welcome on GitHub at https://github.com/YuheiNakasaka/weighted_rand. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/YuheiNakasaka/weighted_rand/blob/main/CODE_OF_CONDUCT.md).
85
+
86
+ ## License
87
+
88
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
89
+
90
+ ## Code of Conduct
91
+
92
+ Everyone interacting in the WeightedRand project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/YuheiNakasaka/weighted_rand/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << 'test'
8
+ t.libs << 'lib'
9
+ t.test_files = FileList['test/**/test_*.rb']
10
+ end
11
+
12
+ task default: :test
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WeightedRand
4
+ # BinarySearch
5
+ # https://qiita.com/kaityo256/items/64c12bb8c8946d7f03c6
6
+ #
7
+ # Initialization: O(N)
8
+ # Search: O(log(N))
9
+ # Update: O(N)
10
+ class BinarySearch
11
+ # Initialize a new WeightedRand object
12
+ #
13
+ # @param [Hash] items the weighted item(eg. {'a' => 2, 'b' => 3, 'c' => 5})
14
+ # @return [WeightedRand] a new WeightedRand object
15
+ def initialize(items)
16
+ raise WrongArgumentError unless items.is_a?(Hash)
17
+
18
+ @running_total = 0
19
+ @items = []
20
+ items.each do |k, v|
21
+ next if v == 0
22
+ @running_total += v
23
+ @items << [k, @running_total]
24
+ end
25
+ end
26
+
27
+ # Return a random item
28
+ #
29
+ # @return [Object] a random item
30
+ def sample
31
+ return nil if @items.empty?
32
+
33
+ rnd = rand(@running_total)
34
+ i = 0
35
+ j = @items.length - 1
36
+ while i < j
37
+ h = (i + j) >> 1
38
+ if @items[h][1] <= rnd
39
+ i = h + 1
40
+ else
41
+ j = h
42
+ end
43
+ end
44
+ @items[i][0]
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WeightedRand
4
+ class WrongArgumentError < StandardError
5
+ def initialize(msg = 'The argument is not a Hash')
6
+ super
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WeightedRand
4
+ # Linear
5
+ #
6
+ # Initialization: O(N)
7
+ # Search: O(N)
8
+ # Update: O(N)
9
+ class Linear
10
+ # Initialize a new WeightedRand object
11
+ #
12
+ # @param [Hash] items the weighted item(eg. {'a' => 2, 'b' => 3, 'c' => 5})
13
+ # @return [WeightedRand] a new WeightedRand object
14
+ def initialize(items)
15
+ raise WrongArgumentError unless items.is_a?(Hash)
16
+
17
+ @running_total = 0
18
+ @items = []
19
+ items.each do |k, v|
20
+ next if v == 0
21
+ @running_total += v
22
+ @items << [k, @running_total]
23
+ end
24
+ end
25
+
26
+ # Return a random item
27
+ #
28
+ # @return [Object] a random item
29
+ def sample
30
+ return nil if @items.empty?
31
+
32
+ rnd = rand(@running_total)
33
+ @items.each do |k, v|
34
+ if v > rnd
35
+ return k
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WeightedRand
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WeightedRand
4
+ # WalkerAlias
5
+ # https://qiita.com/kaityo256/items/64c12bb8c8946d7f03c6
6
+ # https://qiita.com/kaityo256/items/1656597198cbfeb7328c
7
+ #
8
+ # Initialization: O(N)
9
+ # Search: O(1)
10
+ # Update: O(N)
11
+ class WalkerAlias
12
+ # Initialize a new WeightedRand object
13
+ #
14
+ # @param [Hash] items the weighted item(eg. {'a' => 2, 'b' => 3, 'c' => 5})
15
+ # @return [WeightedRand] a new WeightedRand object
16
+ def initialize(items)
17
+ raise WrongArgumentError unless items.is_a?(Hash)
18
+
19
+ @sum = 0
20
+ @threshold = items.map do |k, v|
21
+ @sum += v
22
+ [k, v]
23
+ end
24
+
25
+ @ave = @sum / @threshold.length
26
+
27
+ large = []
28
+ small = []
29
+
30
+ @threshold.length.times do |i|
31
+ if @threshold[i][1] < @ave
32
+ small.push(i)
33
+ else
34
+ large.push(i)
35
+ end
36
+ end
37
+
38
+ @indexes = Array.new(@threshold.length, 0)
39
+
40
+ while !small.empty? && !large.empty?
41
+ j = small.pop
42
+ k = large[-1]
43
+ @indexes[j] = k
44
+ @threshold[k][1] = @threshold[k][1] - (@ave - @threshold[j][1])
45
+ if @threshold[k][1] <= @ave
46
+ small << k
47
+ large.pop
48
+ end
49
+ end
50
+ end
51
+
52
+ # Return a random item
53
+ #
54
+ # @return [Object] a random item
55
+ def sample
56
+ return nil if @sum == 0
57
+
58
+ i = rand(@indexes.length)
59
+ if @threshold[i][1] > rand(@ave)
60
+ return @threshold[i][0]
61
+ else
62
+ return @threshold[@indexes[i]][0]
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'weighted_rand/version'
4
+ require 'weighted_rand/linear'
5
+ require 'weighted_rand/binary_search'
6
+ require 'weighted_rand/walker_alias'
7
+ require 'weighted_rand/errors'
@@ -0,0 +1,4 @@
1
+ module WeightedRand
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/weighted_rand/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'weighted_rand'
7
+ spec.version = WeightedRand::VERSION
8
+ spec.authors = ['YuheiNakasaka']
9
+ spec.email = ['yuhei.nakasaka@gmail.com']
10
+
11
+ spec.summary = 'Weighted random selection for Ruby'
12
+ spec.description = 'Provides a method to select a element by weighted randomization from a hash with weights.'
13
+ spec.homepage = 'https://github.com/YuheiNakasaka/weighted_rand'
14
+ spec.license = 'MIT'
15
+ spec.required_ruby_version = '>= 2.7.0'
16
+
17
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
18
+
19
+ spec.metadata['homepage_uri'] = spec.homepage
20
+ spec.metadata['source_code_uri'] = 'https://github.com/YuheiNakasaka/weighted_rand'
21
+ spec.metadata['changelog_uri'] = 'https://github.com/YuheiNakasaka/weighted_rand/blob/main/CHANGELOG.md'
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
28
+ end
29
+ end
30
+ spec.bindir = 'exe'
31
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
32
+ spec.require_paths = ['lib']
33
+ spec.metadata = {
34
+ 'rubygems_mfa_required' => 'true'
35
+ }
36
+ end
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: weighted_rand
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - YuheiNakasaka
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-01-18 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Provides a method to select a element by weighted randomization from
14
+ a hash with weights.
15
+ email:
16
+ - yuhei.nakasaka@gmail.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".rubocop.yml"
22
+ - ".ruby-version"
23
+ - ".vscode/settings.json"
24
+ - CHANGELOG.md
25
+ - CODE_OF_CONDUCT.md
26
+ - Gemfile
27
+ - Gemfile.lock
28
+ - LICENSE.txt
29
+ - README.md
30
+ - Rakefile
31
+ - lib/weighted_rand.rb
32
+ - lib/weighted_rand/binary_search.rb
33
+ - lib/weighted_rand/errors.rb
34
+ - lib/weighted_rand/linear.rb
35
+ - lib/weighted_rand/version.rb
36
+ - lib/weighted_rand/walker_alias.rb
37
+ - sig/weighted_rand.rbs
38
+ - weighted_rand.gemspec
39
+ homepage: https://github.com/YuheiNakasaka/weighted_rand
40
+ licenses:
41
+ - MIT
42
+ metadata:
43
+ rubygems_mfa_required: 'true'
44
+ post_install_message:
45
+ rdoc_options: []
46
+ require_paths:
47
+ - lib
48
+ required_ruby_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: 2.7.0
53
+ required_rubygems_version: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: '0'
58
+ requirements: []
59
+ rubygems_version: 3.3.7
60
+ signing_key:
61
+ specification_version: 4
62
+ summary: Weighted random selection for Ruby
63
+ test_files: []