From 4693e7bf7352accba96352d9dcf9fa63427cf2f3 Mon Sep 17 00:00:00 2001 From: ricola Date: Sun, 6 Apr 2025 17:04:31 -0600 Subject: [PATCH] Add class for Majority Judgment --- mj.rb | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 mj.rb diff --git a/mj.rb b/mj.rb new file mode 100644 index 0000000..441db5c --- /dev/null +++ b/mj.rb @@ -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