Владимир обнови решението на 15.10.2013 17:59 (преди около 11 години)
+class Integer
+
+ def prime?
+ 2.upto Math.sqrt(self).to_i do |div|
+ return false if (self % div).zero?
+ end
+
+ return true
+ end
+
+ def prime_factors
+ surplus, result = self, []
+
+ while surplus > 0
+ div, surplus = surplus.first_prime_factor
+
+ result << div
+ end
+
+ result
+ end
+
+ def harmonic
+ raise ArgumentError.new('Expecting a natural number') unless natural?
+
+ (1..self).inject(0.to_r) do |sum, n|
+ sum += Rational(1,n)
+ end
+ end
+
+ def digits
+ self.to_s.chars.map(&:to_i)
+ end
+
+ protected
+
+ def first_prime_factor
+ 2.upto Math.sqrt(self).to_i do |div|
+ next unless div.prime?
+
+ return div, (self / div) if (self % div).zero?
+ end
+
+ return self, 0
+ end
+
+ def natural?
+ self >= 0
+ end
+
+end
+
+class Array
+
+ def frequencies
+ result = Hash.new
+
+ self.uniq.each do |el|
+ result[el] = self.count(el)
+ end
+
+ result
+ end
+
+ def average
+ raise ArgumentError.new("Expecting a non-empty array") if size.zero?
+
+ sum = self.inject(0.0){|sum, n| sum + n}
+
+ sum / size
+ end
+
+ def drop_every(n)
+ result = []
+
+ self.each_with_index do |el, i|
+ result << el unless ((i + 1) % n).zero?
+ end
+
+ result
+ end
+
+ def combine_with(other)
+ result = []
+ max_size = [self.size, other.size].max
+
+ 0.upto(max_size) do |i|
+ result << self[i] if self[i]
+ result << other[i] if other[i]
+ end
+
+ result
+ end
+
+end