Add class for Majority Judgment
This commit is contained in:
parent
46c8745a9e
commit
4693e7bf73
1 changed files with 63 additions and 0 deletions
63
mj.rb
Normal file
63
mj.rb
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
class MajorityJudgment
|
||||
|
||||
include Comparable
|
||||
attr_reader :ratings, :count, :n, :majority
|
||||
|
||||
def initialize(arg)
|
||||
if arg.is_a?(Array)
|
||||
@ratings = arg
|
||||
@count = { }
|
||||
@n = 0
|
||||
ratings.each do |r|
|
||||
@count.has_key?(r) ? @count[r] = @count[r] + 1 : @count[r] = 1
|
||||
@n = @n + 1
|
||||
end
|
||||
elsif arg.is_a?(Hash)
|
||||
@count = arg
|
||||
@n = 0
|
||||
@count.collect { |r, c| @n = @n + c }
|
||||
end
|
||||
@majority = ( @n.to_f / 2 ).floor + 1
|
||||
end
|
||||
|
||||
def mj
|
||||
s = 0
|
||||
(1..6).to_a.reverse.each do |r|
|
||||
s = s + @count[r] if @count[r]
|
||||
return r if s >= @majority
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
def proponents(rating = self.mj)
|
||||
p = 0
|
||||
(rating+1..6).to_a.reverse.each do |r|
|
||||
p = p + @count[r] if @count[r]
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
def opponents(rating = self.mj)
|
||||
o = 0
|
||||
(1..rating-1).to_a.reverse.each do |r|
|
||||
o = o + @count[r] if @count[r]
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
def <=> (other)
|
||||
return 1 if self.mj > other.mj
|
||||
return -1 if self.mj < other.mj
|
||||
return 0 if self.mj == 0
|
||||
counta = self.count.dup
|
||||
counta[self.mj] = counta[self.mj] - 1
|
||||
countb = other.count.dup
|
||||
countb[other.mj] = countb[other.mj] - 1
|
||||
return MajorityJudgment.new(counta) <=> MajorityJudgment.new(countb)
|
||||
end
|
||||
|
||||
def to_s
|
||||
puts "#{@count}: {M=>#{self.mj}, P=>#{self.proponents}, O=>#{self.opponents}}"
|
||||
end
|
||||
|
||||
end
|
||||
Loading…
Add table
Add a link
Reference in a new issue