weightedpicker 0.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ lib/**/*.rb
2
+ bin/*
3
+ -
4
+ features/**/*.feature
5
+ LICENSE.txt
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --color
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ source "http://rubygems.org"
2
+ # Add dependencies required to use your gem here.
3
+ # Example:
4
+ # gem "activesupport", ">= 2.3.5"
5
+
6
+ # Add dependencies to develop your gem here.
7
+ # Include everything needed to run rake, tests, features, etc.
8
+ group :development do
9
+ gem "rspec", "~> 2.9.0"
10
+ gem "rdoc", "~> 3.12"
11
+ gem "bundler", "~> 1.1.3"
12
+ gem "jeweler", "~> 1.8.3"
13
+ gem "simplecov", ">= 0"
14
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,37 @@
1
+ GEM
2
+ remote: http://rubygems.org/
3
+ specs:
4
+ diff-lcs (1.1.3)
5
+ git (1.2.5)
6
+ jeweler (1.8.3)
7
+ bundler (~> 1.0)
8
+ git (>= 1.2.5)
9
+ rake
10
+ rdoc
11
+ json (1.6.6)
12
+ multi_json (1.2.0)
13
+ rake (0.9.2.2)
14
+ rdoc (3.12)
15
+ json (~> 1.4)
16
+ rspec (2.9.0)
17
+ rspec-core (~> 2.9.0)
18
+ rspec-expectations (~> 2.9.0)
19
+ rspec-mocks (~> 2.9.0)
20
+ rspec-core (2.9.0)
21
+ rspec-expectations (2.9.0)
22
+ diff-lcs (~> 1.1.3)
23
+ rspec-mocks (2.9.0)
24
+ simplecov (0.6.1)
25
+ multi_json (~> 1.0)
26
+ simplecov-html (~> 0.5.3)
27
+ simplecov-html (0.5.3)
28
+
29
+ PLATFORMS
30
+ ruby
31
+
32
+ DEPENDENCIES
33
+ bundler (~> 1.1.3)
34
+ jeweler (~> 1.8.3)
35
+ rdoc (~> 3.12)
36
+ rspec (~> 2.9.0)
37
+ simplecov
data/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2012 ippei94da
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,19 @@
1
+ = weightedpicker
2
+
3
+ Description goes here.
4
+
5
+ == Contributing to weightedpicker
6
+
7
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
8
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
9
+ * Fork the project.
10
+ * Start a feature/bugfix branch.
11
+ * Commit and push until you are happy with your contribution.
12
+ * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
13
+ * Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
14
+
15
+ == Copyright
16
+
17
+ Copyright (c) 2012 ippei94da. See LICENSE.txt for
18
+ further details.
19
+
data/Rakefile ADDED
@@ -0,0 +1,52 @@
1
+ # encoding: utf-8
2
+
3
+ require 'rubygems'
4
+ require 'bundler'
5
+ begin
6
+ Bundler.setup(:default, :development)
7
+ rescue Bundler::BundlerError => e
8
+ $stderr.puts e.message
9
+ $stderr.puts "Run `bundle install` to install missing gems"
10
+ exit e.status_code
11
+ end
12
+ require 'rake'
13
+
14
+ require 'jeweler'
15
+ Jeweler::Tasks.new do |gem|
16
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
17
+ gem.name = "weightedpicker"
18
+ gem.homepage = "http://github.com/ippei94da/weightedpicker"
19
+ gem.license = "MIT"
20
+ gem.summary = %Q{Picking one item from list with weight}
21
+ gem.description = %Q{This library enable to pick out items with their weight.
22
+ Weight data is storaged as a YAML file.
23
+ You can use this library for music player, wallpaper changer, language training.
24
+ }
25
+ gem.email = "ippei94da@gmail.com"
26
+ gem.authors = ["ippei94da"]
27
+ # dependencies defined in Gemfile
28
+ end
29
+ Jeweler::RubygemsDotOrgTasks.new
30
+
31
+ require 'rspec/core'
32
+ require 'rspec/core/rake_task'
33
+ RSpec::Core::RakeTask.new(:spec) do |spec|
34
+ spec.pattern = FileList['spec/**/*_spec.rb']
35
+ end
36
+
37
+ RSpec::Core::RakeTask.new(:rcov) do |spec|
38
+ spec.pattern = 'spec/**/*_spec.rb'
39
+ spec.rcov = true
40
+ end
41
+
42
+ task :default => :spec
43
+
44
+ require 'rdoc/task'
45
+ Rake::RDocTask.new do |rdoc|
46
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
47
+
48
+ rdoc.rdoc_dir = 'rdoc'
49
+ rdoc.title = "weightedpicker #{version}"
50
+ rdoc.rdoc_files.include('README*')
51
+ rdoc.rdoc_files.include('lib/**/*.rb')
52
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.0.0
@@ -0,0 +1,233 @@
1
+ require 'yaml'
2
+
3
+ # TODO
4
+ # initialize.指定したファイル内のデータが WeightedPicker 的に
5
+ # 解釈できなければ例外。
6
+
7
+ #= 概要
8
+ # 要素群の中から、優先度に応じた重み付きランダムで、
9
+ # どれか1つを選択する。
10
+ # たとえば、以下の用途に使える。
11
+ #* 音楽ファイルの再生(好みのものは多い頻度で、
12
+ # そうでないものは少ない頻度で)
13
+ #* クイズゲームの問題選択
14
+ #* 画像
15
+ # * 写真で壁紙, スライドショー的な用途。
16
+ #
17
+ # 対象の要素はファイルであることを前提としない。
18
+ # 文字列であることが多いかもしれない。
19
+ #
20
+ #= 確率として評価を保存
21
+ # 全ての要素の好ましさを点数として記録。
22
+ # 対象要素全てで好ましさを総和したものが母数、
23
+ # それに対する要素の点数/点数の総和 がその要素の選択される確率。
24
+ #
25
+ #= 保存ファイルが必要
26
+ # 保存ファイル名を必ず保持する。
27
+ # 当クラスは、中長期的に使用することで選択を賢くするのが目的。
28
+ # 現在の成績を保存しないということはほとんど考えられない。
29
+ #
30
+ #= 時間を評価関数に入れない
31
+ # 「対象の要素の好ましさの、好ましさの総量に対する割合」が
32
+ # その要素が選ばれる確率となる。
33
+ # 時間を評価に入れると構造が複雑になるし、
34
+ # 機会と時間は一般にそれほどよい相関がない。
35
+ # 毎日使うこともあれば、1ヶ月あくこともある。
36
+ #
37
+ #= 使用 != 鑑賞
38
+ # ライブラリの考え方としては使用=鑑賞とは仮定しない。
39
+ # 要素が pick された瞬間では点数操作は行わず、
40
+ # 明示的に点数操作が指示されたときだけ変化・保存する。
41
+ #
42
+ #= 加点と減点
43
+ # 点数操作が行われる度に規格化する。
44
+ #
45
+ #= 評価の上限と下限
46
+ #== 上限
47
+ # 点数の上限は 1.0。
48
+ # 上限を越える点数の要素が現れたら、
49
+ # それが 1.0 になるように全ての要素の評価を除算して正規化する。
50
+ #
51
+ #== 下限
52
+ # 点数の下限は 2.0 ** (-500) としておく。
53
+ # 下限を下回る点数の要素が現れたら、
54
+ # その要素の点数を下限値に設定する。
55
+ # これが重要になるのはクイズゲームで間違ったときにその問題以外の
56
+ # 評価が相対的に下がる現象。
57
+ # Ruby 1.9.1 において扱える最小の数を確認してみたところ、
58
+ # 2.0 **(-1074) # => 5.0e-324
59
+ # 2.0 **(-1075) # => 0.0
60
+ # となり、無限小の有限の数が扱えず、
61
+ # どこかで潰れて 0.0 になることが分かる。
62
+ # 指数 -500 は有限の数から 0.0 になる境界と
63
+ # 最頻値 1.0 の中間くらいの指数として選ばれた。
64
+ #
65
+ # 1/100万で人間的尺度では無視して良い確率だが、
66
+ # これを大きく下回る確率としている。
67
+ # 普通 500 回も間違えることは考えにくい。
68
+ # そして 500回間違えたとしても、
69
+ # 2.0 **(- 500) 精度で評価が保存可能。
70
+ #
71
+ # ただし、0.0 がセットされた要素はこれを下限値に修正したりはせず、
72
+ # 0.0 のままとする。
73
+ # これは たとえばメイドさんRnR のように自動的には選ばれて
74
+ # 欲しくないものだけど、ファイルを消すのは惜しいものを扱うため。
75
+ # また、既にデータ管理がなされていることを示す必要がある。
76
+ #
77
+ #= 連続選択を制限する方法は導入しない
78
+ # いろいろ複雑になる。
79
+ # とりあえずはこの仕組みを導入しない。
80
+ # これに対応するにはまず history をデータとして残す必要がある。
81
+ # また計算通りの確率から乱れない方法が好ましいが、
82
+ # そのような計算方法はぱっと思い付かない。
83
+ #
84
+ # たとえば定数回以内の選択を拒否する仕組みでは、
85
+ # 重み 100 が1個(A)と重み1が1個(B)で全2個状態では、
86
+ # 連続を認めない(間に 1つ入れる必要あり)という場合では、
87
+ # 本来 99:1 で実行される筈なのに 1:1 になってしまう。
88
+ #
89
+ # 間隔の期待値に定数を除算する方法も考えたが、
90
+ # 重み0のものはゼロ割りになるなど扱いが面倒になる。
91
+ #
92
+ # ヒストリ関係はこのクラスの外に出した方が良いと判断。
93
+ class WeightedPicker
94
+ MAX_WEIGHT = 1.0
95
+ MIN_WEIGHT = 2.0 ** (-500)
96
+
97
+ class InvalidFilenameError < Exception; end
98
+ class NoEntryError < Exception; end
99
+ class NotExistKeyError < Exception; end
100
+
101
+ # Initialization.
102
+ # Argument 'file' indicates a strage file name for data
103
+ # which this class manages.
104
+ # If the 'file' does not exist, this file is used to data strage.
105
+ #
106
+ # Argument 'items' is an array of items to be managed.
107
+ # Not all the items in the 'file' survive.
108
+ # A and B in the file and B and C in items,
109
+ # then B and C is the items which this class manage.
110
+ # A is discarded from record.
111
+ def initialize(file, items)
112
+ @save_file = file
113
+ unless File.exist? @save_file
114
+ File.open(@save_file, "w") {|io| YAML.dump({}, io)}
115
+ end
116
+ @weights = YAML.load_file(file)
117
+
118
+ merge(items)
119
+ normalize_write
120
+ end
121
+
122
+ #乱数を利用して優先度で重み付けして要素を選び、要素を返す。
123
+ def pick
124
+ raise NoEntryError if @weights.empty?
125
+
126
+ ##乱数を 2つ生成し、adopt? を呼ぶ。
127
+ ##乱数でどれか1つを選ぶ。
128
+ ##その priority に応じて、確率で採用する。
129
+ while ( true )
130
+ item = @weights.keys[ rand( @weights.size ) ]
131
+
132
+ #next if ( ! pick?( item ) )
133
+ if adopt?( item, rand )
134
+ return item
135
+ end
136
+ end
137
+ end
138
+
139
+ #重みを重くする。(優先度が上がる)
140
+ def weigh(item)
141
+ #pp @weights
142
+ raise NotExistKeyError unless @weights.has_key?(item)
143
+ @weights[ item ] *= 2.0
144
+ normalize_write
145
+ end
146
+
147
+ #重みを軽くする。(優先度が下がる)
148
+ def lighten( item )
149
+ raise NotExistKeyError unless @weights.has_key?(item)
150
+ @weights[ item ] /= 2.0
151
+ normalize_write
152
+ end
153
+
154
+ ##管理している要素の数を返す。
155
+ #def size
156
+ # @weights.size
157
+ #end
158
+
159
+ ##管理している要素と重みでイテレート。
160
+ ##e.g. ws0.each { |item, weight| p item, weight }
161
+ ##item が管理しているオブジェクト、weight が重み。
162
+ #def each
163
+ # @weights.each do |item, weight|
164
+ # yield( item, weight )
165
+ # end
166
+ #end
167
+
168
+ private
169
+
170
+ # 引数 keys で示したものと、
171
+ # 内部的に管理しているデータが整合しているかチェックし、
172
+ # keys に合わせる。
173
+ # 追加されたデータは MAX_WEIGHT の重みとなる。
174
+ # データが削除された場合、それが最大値の可能性があるので
175
+ # 必ず normalize_write される。
176
+ def merge(keys)
177
+ keys.each do |key|
178
+ @weights[key] = MAX_WEIGHT unless
179
+ @weights.keys.include?(key)
180
+ end
181
+ @weights.each do |key, val|
182
+ @weights.delete(key) unless keys.include?(key)
183
+ end
184
+ normalize_write
185
+ end
186
+
187
+ # given_val は 0.0〜1.0 の間の実数とする。
188
+ # 重みと 与えられた given_val が等しい場合は false になる。
189
+ # これは重み 1.0 が稀に採用されないことがあっても
190
+ # 重み 0.0 が稀にでも採用されることを嫌ってのこと。
191
+ def adopt?( item, given_val )
192
+ raise NotExistKeyError unless @weights.has_key?(item)
193
+
194
+ return given_val < (@weights[item])
195
+ end
196
+
197
+ ##データを更新し、整合性を確保する。
198
+ #def refresh
199
+ # TODO
200
+ # raise れいがいめい
201
+ # "Cannot do refresh because no entry exists." if @weights.size == 0
202
+
203
+ # #normalize のために事前設定。
204
+ # @max_weight = @weights.max{ |a, b| a[1] <=> b[1] }[1]
205
+ # normalize
206
+
207
+ # #normalize したあとのデータに従い、total_weight などを算出。
208
+ # @total_weight = @weights.values.inject( 0 ){ |sum, i| sum += i }
209
+ # @max_weight = @weights.max{ |a, b| a[1] <=> b[1] }[1]
210
+ #end
211
+
212
+ # 最大値を max とするように規格化する。
213
+ # ただし、weight が MIN_WEIGHT 未満となった項目は
214
+ # MIN_WEIGHT を新しい weight とする。
215
+ def normalize_write
216
+ raise NoEntryError if @weights.size == 0
217
+
218
+ old_max = @weights.values.max
219
+ @weights.each do |key, val|
220
+ new_val = (val * (MAX_WEIGHT / old_max ) )
221
+ if new_val < MIN_WEIGHT
222
+ @weights[key] = MIN_WEIGHT
223
+ else
224
+ @weights[key] = new_val
225
+ end
226
+ end
227
+
228
+ File.open(@save_file, "w") do |io|
229
+ YAML.dump(@weights, io)
230
+ end
231
+ end
232
+
233
+ end
@@ -0,0 +1,12 @@
1
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
2
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
3
+ require 'rspec'
4
+ require 'weightedpicker'
5
+
6
+ # Requires supporting files with custom matchers and macros, etc,
7
+ # in ./support/ and its subdirectories.
8
+ Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
9
+
10
+ RSpec.configure do |config|
11
+
12
+ end
@@ -0,0 +1,292 @@
1
+ require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
2
+ require "stringio"
3
+ require "fileutils"
4
+
5
+ class WeightedPicker
6
+ attr_accessor :weights
7
+ public :normalize_write, :adopt?, :merge
8
+ end
9
+
10
+ TMP_FILE = "tmp.yaml"
11
+ NOT_EXIST_FILE = "not_exist_file"
12
+
13
+
14
+
15
+ describe "Weightedpicker::initialize" do
16
+ before do
17
+ weights = { "A" => 1.0, "B" => 0.5, }
18
+ items = ["A", "B"]
19
+ File.open(TMP_FILE, "w") { |io| YAML.dump(weights, io) }
20
+ @wp01 = WeightedPicker.new(TMP_FILE, items)
21
+ @wp02 = Marshal.load(Marshal.dump(@wp01))
22
+ @wp02.weights = {}
23
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
24
+ end
25
+
26
+ it "should create new file when the file not exist" do
27
+ # 指定したファイルが存在しない場合、
28
+ t = WeightedPicker.new(NOT_EXIST_FILE, ["A","B"])
29
+ t.weights.should == { "A" => 1.0, "B" => 1.0}
30
+ YAML.load_file(NOT_EXIST_FILE).should == { "A" => 1.0, "B" => 1.0, }
31
+ end
32
+
33
+ it "should raise exception" do
34
+ # 作成できないファイル名。
35
+ lambda{WeightedPicker.new("", ["A","B"])}.should raise_error(Errno::ENOENT)
36
+ end
37
+
38
+ it "should read correctly" do
39
+ # 正しく取り込めているか?
40
+ @wp01.weights.should == { "A" => 1.0, "B" => 0.5, }
41
+ end
42
+
43
+ it "should normalize when the maximum in the file not the same as MAX_WEIGHT" do
44
+ # 指定したファイル内の重みの最大値が MAX_WEIGHT と異なれば、
45
+ # 全体を normalize して格納。
46
+ weights = { "A" => 2.0, "B" => 0.5, }
47
+ File.open(TMP_FILE, "w") {|io| YAML.dump(weights, io) }
48
+ WeightedPicker.new(TMP_FILE, ["A","B"]).weights.should == { "A" => 1.0, "B" => 0.25, }
49
+ #
50
+ weights = { "A" => 0.25, "B" => 0.5, }
51
+ File.open(TMP_FILE, "w"){ |io| YAML.dump(weights, io) }
52
+ WeightedPicker.new(TMP_FILE, ["A","B"]).weights.should == { "A" => 0.5, "B" => 1.0, }
53
+ end
54
+
55
+ it "should merge when keys between weights and items" do
56
+ # weights と items が異なる場合
57
+ weights = { "A" => 1.0, "B" => 0.50, }
58
+ File.open(TMP_FILE, "w") {|io| YAML.dump(weights, io) }
59
+ WeightedPicker.new(TMP_FILE, ["B","C"]).weights.should == { "B" => 0.5, "C" => 1.0, }
60
+ end
61
+
62
+ after do
63
+ FileUtils.rm TMP_FILE if File.exist? TMP_FILE
64
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
65
+ end
66
+
67
+ end
68
+
69
+ describe "Weightedpicker::merge" do
70
+ before do
71
+ weights = { "A" => 1.0, "B" => 0.5, }
72
+ items = ["A", "B"]
73
+ File.open(TMP_FILE, "w") { |io| YAML.dump(weights, io) }
74
+ @wp01 = WeightedPicker.new(TMP_FILE, items)
75
+
76
+ @wp02 = Marshal.load(Marshal.dump(@wp01))
77
+ @wp02.weights = {}
78
+
79
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
80
+ end
81
+
82
+ it "when keys given are less than weights file" do
83
+ # 少ない場合
84
+ t = Marshal.load(Marshal.dump(@wp01))
85
+ keys = ["B"]
86
+ t.merge(keys)
87
+ t.weights. should == { "B" => 1.0 }
88
+ # 書き込みチェック
89
+ YAML.load_file(TMP_FILE).should == { "B" => 1.0 }
90
+ end
91
+
92
+ it "when keys given are more than weights file" do
93
+ # 多い場合
94
+ t = Marshal.load(Marshal.dump(@wp01))
95
+ keys = ["A", "B", "C"]
96
+ t.merge(keys)
97
+ t.weights.should == { "A" => 1.0, "B" => 0.5, "C" => 1.0, }
98
+ # 書き込みチェック
99
+ YAML.load_file(TMP_FILE).should == { "A" => 1.0, "B" => 0.5, "C" => 1.0}
100
+ end
101
+
102
+ it "when keys given are the same as weights file" do
103
+ t = Marshal.load(Marshal.dump(@wp01))
104
+ # 同じ場合
105
+ keys = ["A", "B"]
106
+ t.merge(keys)
107
+ t.weights.should == { "A" => 1.0, "B" => 0.5}
108
+ # 書き込みチェック
109
+ YAML.load_file(TMP_FILE).should == { "A" => 1.0, "B" => 0.5}
110
+ end
111
+
112
+ after do
113
+ FileUtils.rm TMP_FILE if File.exist? TMP_FILE
114
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
115
+ end
116
+
117
+ end
118
+
119
+ describe "Weightedpicker::pick" do
120
+ before do
121
+ weights = { "A" => 1.0, "B" => 0.5, }
122
+ items = ["A", "B"]
123
+ File.open(TMP_FILE, "w") { |io| YAML.dump(weights, io) }
124
+ @wp01 = WeightedPicker.new(TMP_FILE, items)
125
+
126
+ @wp02 = Marshal.load(Marshal.dump(@wp01))
127
+ @wp02.weights = {}
128
+
129
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
130
+ end
131
+
132
+ it "should pick" do
133
+ ## No test, beccause including randomness.
134
+ #assert_raise(WeightedPicker::NoEntryError){@wp02.pick}
135
+ #100.times do
136
+ # assert_equal(true, ["A","B"].include?(@wp01.pick))
137
+ #end
138
+ end
139
+
140
+ after do
141
+ FileUtils.rm TMP_FILE if File.exist? TMP_FILE
142
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
143
+ end
144
+
145
+ end
146
+
147
+ describe "Weightedpicker::weigh" do
148
+ before do
149
+ weights = { "A" => 1.0, "B" => 0.5, }
150
+ items = ["A", "B"]
151
+ File.open(TMP_FILE, "w") { |io| YAML.dump(weights, io) }
152
+ @wp01 = WeightedPicker.new(TMP_FILE, items)
153
+ @wp02 = Marshal.load(Marshal.dump(@wp01))
154
+ @wp02.weights = {}
155
+
156
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
157
+ end
158
+
159
+ it "should weigh A" do
160
+ t = Marshal.load(Marshal.dump(@wp01))
161
+ t.weigh("A")
162
+ t.weights.should == { "A" => 1.0, "B" => 0.25 }
163
+ # 書き込みチェック
164
+ YAML.load_file(TMP_FILE).should == { "A" => 1.0, "B" => 0.25 }
165
+ end
166
+
167
+ it "should weigh B" do
168
+ t = Marshal.load(Marshal.dump(@wp01))
169
+ t.weigh("B")
170
+ t.weights.should == { "A" => 1.0, "B" => 1.0 }
171
+ # 書き込みチェック
172
+ YAML.load_file(TMP_FILE).should == { "A" => 1.0, "B" => 1.0 }
173
+ end
174
+
175
+ it "should raise error" do
176
+ lambda{Marshal.load(Marshal.dump(@wp01)).weigh("C")}.should raise_error(WeightedPicker::NotExistKeyError)
177
+ end
178
+
179
+ after do
180
+ FileUtils.rm TMP_FILE if File.exist? TMP_FILE
181
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
182
+ end
183
+
184
+ end
185
+
186
+ describe "Weightedpicker::lighten" do
187
+ before do
188
+ weights = { "A" => 1.0, "B" => 0.5, }
189
+ items = ["A", "B"]
190
+ File.open(TMP_FILE, "w") { |io| YAML.dump(weights, io) }
191
+ @wp01 = WeightedPicker.new(TMP_FILE, items)
192
+ @wp02 = Marshal.load(Marshal.dump(@wp01))
193
+ @wp02.weights = {}
194
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
195
+ end
196
+
197
+ it "should lighten A" do
198
+ t = Marshal.load(Marshal.dump(@wp01))
199
+ t.lighten("A")
200
+ t.weights.should == { "A" => 1.0, "B" => 1.0 }
201
+ # 書き込みチェック
202
+ YAML.load_file(TMP_FILE).should == { "A" => 1.0, "B" => 1.0 }
203
+ end
204
+
205
+ it "should lighten B" do
206
+ t = Marshal.load(Marshal.dump(@wp01))
207
+ t.lighten("B")
208
+ t.weights.should == { "A" => 1.0, "B" => 0.25 }
209
+ # 書き込みチェック
210
+ YAML.load_file(TMP_FILE).should == { "A" => 1.0, "B" => 0.25 }
211
+ end
212
+
213
+ it "should raise error" do
214
+ t = Marshal.load(Marshal.dump(@wp01))
215
+ lambda{t.lighten("C")}.should raise_error(WeightedPicker::NotExistKeyError)
216
+ end
217
+
218
+ after do
219
+ FileUtils.rm TMP_FILE if File.exist? TMP_FILE
220
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
221
+ end
222
+
223
+ end
224
+
225
+ describe "Weightedpicker::adopt" do
226
+ before do
227
+ weights = { "A" => 1.0, "B" => 0.5, }
228
+ items = ["A", "B"]
229
+ File.open(TMP_FILE, "w") { |io| YAML.dump(weights, io) }
230
+ @wp01 = WeightedPicker.new(TMP_FILE, items)
231
+ @wp02 = Marshal.load(Marshal.dump(@wp01))
232
+ @wp02.weights = {}
233
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
234
+ end
235
+
236
+ it do
237
+ @wp01.adopt?("A", 0.0 ).should be_true
238
+ @wp01.adopt?("A", 0.5 ).should be_true
239
+ @wp01.adopt?("A", 0.999).should be_true
240
+ @wp01.adopt?("A", 1.0 ).should be_false
241
+ @wp01.adopt?("B", 0.0 ).should be_true
242
+ @wp01.adopt?("B", 0.499).should be_true
243
+ @wp01.adopt?("B", 0.5 ).should be_false
244
+ @wp01.adopt?("B", 1.0 ).should be_false
245
+ end
246
+
247
+ after do
248
+ FileUtils.rm TMP_FILE if File.exist? TMP_FILE
249
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
250
+ end
251
+
252
+ end
253
+
254
+ describe "Weightedpicker::normalize_write" do
255
+ before do
256
+ weights = { "A" => 1.0, "B" => 0.5, }
257
+ items = ["A", "B"]
258
+ File.open(TMP_FILE, "w") { |io| YAML.dump(weights, io) }
259
+ @wp01 = WeightedPicker.new(TMP_FILE, items)
260
+ @wp02 = Marshal.load(Marshal.dump(@wp01))
261
+ @wp02.weights = {}
262
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
263
+ end
264
+
265
+ it "should shrink write" do
266
+ t = Marshal.load(Marshal.dump(@wp01))
267
+ t.weights = { "A" => 2.0, "B" => 0.5, }
268
+ t.normalize_write
269
+ t.weights.should == { "A" => 1.0, "B" => 0.25}
270
+ # 書き込みチェック
271
+ YAML.load_file(TMP_FILE).should == { "A" => 1.0, "B" => 0.25}
272
+ end
273
+
274
+ it "should shrink write" do
275
+ t = Marshal.load(Marshal.dump(@wp01))
276
+ t.weights = { "A" => 0.5, "B" => 0.5, }
277
+ t.normalize_write
278
+ t.weights.should == { "A" => 1.0, "B" => 1.00}
279
+ # 書き込みチェック
280
+ YAML.load_file(TMP_FILE).should == { "A" => 1.0, "B" => 1.00}
281
+ end
282
+
283
+ it "should raise error" do
284
+ lambda{@wp02.normalize_write}.should raise_error (WeightedPicker::NoEntryError)
285
+ end
286
+
287
+ after do
288
+ FileUtils.rm TMP_FILE if File.exist? TMP_FILE
289
+ FileUtils.rm NOT_EXIST_FILE if File.exist? NOT_EXIST_FILE
290
+ end
291
+
292
+ end
@@ -0,0 +1,63 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE DIRECTLY
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = "weightedpicker"
8
+ s.version = "0.0.0"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["ippei94da"]
12
+ s.date = "2012-04-13"
13
+ s.description = "This library enable to pick out items with their weight.\n Weight data is storaged as a YAML file.\n You can use this library for music player, wallpaper changer, language training.\n "
14
+ s.email = "ippei94da@gmail.com"
15
+ s.extra_rdoc_files = [
16
+ "LICENSE.txt",
17
+ "README.rdoc"
18
+ ]
19
+ s.files = [
20
+ ".document",
21
+ ".rspec",
22
+ "Gemfile",
23
+ "Gemfile.lock",
24
+ "LICENSE.txt",
25
+ "README.rdoc",
26
+ "Rakefile",
27
+ "VERSION",
28
+ "lib/weightedpicker.rb",
29
+ "spec/spec_helper.rb",
30
+ "spec/weightedpicker_spec.rb",
31
+ "weightedpicker.gemspec"
32
+ ]
33
+ s.homepage = "http://github.com/ippei94da/weightedpicker"
34
+ s.licenses = ["MIT"]
35
+ s.require_paths = ["lib"]
36
+ s.rubygems_version = "1.8.21"
37
+ s.summary = "Picking one item from list with weight"
38
+
39
+ if s.respond_to? :specification_version then
40
+ s.specification_version = 3
41
+
42
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
43
+ s.add_development_dependency(%q<rspec>, ["~> 2.9.0"])
44
+ s.add_development_dependency(%q<rdoc>, ["~> 3.12"])
45
+ s.add_development_dependency(%q<bundler>, ["~> 1.1.3"])
46
+ s.add_development_dependency(%q<jeweler>, ["~> 1.8.3"])
47
+ s.add_development_dependency(%q<simplecov>, [">= 0"])
48
+ else
49
+ s.add_dependency(%q<rspec>, ["~> 2.9.0"])
50
+ s.add_dependency(%q<rdoc>, ["~> 3.12"])
51
+ s.add_dependency(%q<bundler>, ["~> 1.1.3"])
52
+ s.add_dependency(%q<jeweler>, ["~> 1.8.3"])
53
+ s.add_dependency(%q<simplecov>, [">= 0"])
54
+ end
55
+ else
56
+ s.add_dependency(%q<rspec>, ["~> 2.9.0"])
57
+ s.add_dependency(%q<rdoc>, ["~> 3.12"])
58
+ s.add_dependency(%q<bundler>, ["~> 1.1.3"])
59
+ s.add_dependency(%q<jeweler>, ["~> 1.8.3"])
60
+ s.add_dependency(%q<simplecov>, [">= 0"])
61
+ end
62
+ end
63
+
metadata ADDED
@@ -0,0 +1,144 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: weightedpicker
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - ippei94da
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-04-13 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rspec
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: 2.9.0
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ~>
28
+ - !ruby/object:Gem::Version
29
+ version: 2.9.0
30
+ - !ruby/object:Gem::Dependency
31
+ name: rdoc
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ~>
36
+ - !ruby/object:Gem::Version
37
+ version: '3.12'
38
+ type: :development
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ~>
44
+ - !ruby/object:Gem::Version
45
+ version: '3.12'
46
+ - !ruby/object:Gem::Dependency
47
+ name: bundler
48
+ requirement: !ruby/object:Gem::Requirement
49
+ none: false
50
+ requirements:
51
+ - - ~>
52
+ - !ruby/object:Gem::Version
53
+ version: 1.1.3
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ none: false
58
+ requirements:
59
+ - - ~>
60
+ - !ruby/object:Gem::Version
61
+ version: 1.1.3
62
+ - !ruby/object:Gem::Dependency
63
+ name: jeweler
64
+ requirement: !ruby/object:Gem::Requirement
65
+ none: false
66
+ requirements:
67
+ - - ~>
68
+ - !ruby/object:Gem::Version
69
+ version: 1.8.3
70
+ type: :development
71
+ prerelease: false
72
+ version_requirements: !ruby/object:Gem::Requirement
73
+ none: false
74
+ requirements:
75
+ - - ~>
76
+ - !ruby/object:Gem::Version
77
+ version: 1.8.3
78
+ - !ruby/object:Gem::Dependency
79
+ name: simplecov
80
+ requirement: !ruby/object:Gem::Requirement
81
+ none: false
82
+ requirements:
83
+ - - ! '>='
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ type: :development
87
+ prerelease: false
88
+ version_requirements: !ruby/object:Gem::Requirement
89
+ none: false
90
+ requirements:
91
+ - - ! '>='
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ description: ! "This library enable to pick out items with their weight.\n Weight
95
+ data is storaged as a YAML file.\n You can use this library for music player,
96
+ wallpaper changer, language training.\n "
97
+ email: ippei94da@gmail.com
98
+ executables: []
99
+ extensions: []
100
+ extra_rdoc_files:
101
+ - LICENSE.txt
102
+ - README.rdoc
103
+ files:
104
+ - .document
105
+ - .rspec
106
+ - Gemfile
107
+ - Gemfile.lock
108
+ - LICENSE.txt
109
+ - README.rdoc
110
+ - Rakefile
111
+ - VERSION
112
+ - lib/weightedpicker.rb
113
+ - spec/spec_helper.rb
114
+ - spec/weightedpicker_spec.rb
115
+ - weightedpicker.gemspec
116
+ homepage: http://github.com/ippei94da/weightedpicker
117
+ licenses:
118
+ - MIT
119
+ post_install_message:
120
+ rdoc_options: []
121
+ require_paths:
122
+ - lib
123
+ required_ruby_version: !ruby/object:Gem::Requirement
124
+ none: false
125
+ requirements:
126
+ - - ! '>='
127
+ - !ruby/object:Gem::Version
128
+ version: '0'
129
+ segments:
130
+ - 0
131
+ hash: 996808657
132
+ required_rubygems_version: !ruby/object:Gem::Requirement
133
+ none: false
134
+ requirements:
135
+ - - ! '>='
136
+ - !ruby/object:Gem::Version
137
+ version: '0'
138
+ requirements: []
139
+ rubyforge_project:
140
+ rubygems_version: 1.8.21
141
+ signing_key:
142
+ specification_version: 3
143
+ summary: Picking one item from list with weight
144
+ test_files: []