平均数/中间数 mean/median

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

class Array 
    def mean 
        inject(0) {|sum, x| sum += x} / size.to_f
    end
    def median 
        sorted = self.sort() 
        if (sorted.size.modulo(2) == 0) then 
            ((sorted[(sorted.size/2)-1]+sorted[(sorted.size/2)])/2.0) 
        else 
            sorted[sorted.size/2] 
        end 
    end 
    def mode 
        occures = Hash.new(0) 
        self.each{|x| occures[x] += 1 } 
        max = 0 
        modes = [] 
        occures.each{|key, value| 
            if value > max then 
                modes = [key] 
                max = value 
            elsif value == max 
                modes.push(key) 
            end 
        } 
        modes 
    end 
end 

num_list = [92,86,79,64,89,92,88,62,58,95,100,97] 
puts "Mean: #{num_list.mean}" 
puts "Median: #{num_list.median}" 
puts "Mode: #{num_list.mode}"