Слав обнови решението на 13.10.2013 02:50 (преди около 11 години)
+class Integer
+ def prime?
+ if self < 0
+ false
+ else
+ 2.upto(Math.sqrt(self)).all? { |a| self.remainder(a).nonzero? }
+ end
+ end
+
+ def contains_prime(prime)
+ num, counter = self, 0
+ while num % prime == 0
+ counter += 1
+ num /= prime
+ end
+ counter
+ end
+
+ def prime_factors
+ arr, num = [], self.abs
+ prime_arr = 2.upto(num).to_a.select { |a| num % a == 0 and a.prime? }
+ prime_arr.each { |x| arr.push [x] * num.contains_prime(x) }
+ arr.flatten
+ end
+
+ def harmonic
+ 1.upto(self).inject { |product, a| product + Rational(1,a) }
+ end
+
+ def digits
+ self.to_s.chars.map { |a| a.to_i }
+ end
+end
+
+class Array
+ def frequencies
+ arr, freqHash = self, {}
+ while not arr.empty?
+ cnt = arr.count(arr.first)
+ freqHash[arr.first] = cnt
+ arr.delete(arr.first)
+ end
+ freqHash
+ end
+
+ def average
+ self.inject{ |sum,x| sum + x } / self.count.to_f
+ end
+
+ def drop_every(n)
+ arr = []
+ hash = Hash[self.map.with_index.to_a]
+ hash.each { |key, value| arr.push(key) if value % n == 0 }
+ arr
+ end
+
+ def combine_with(other)
+ arr = []
+ while self.any? and other.any?
+ arr.push(self.shift)
+ arr.push(other.shift)
+ end
+ if self.empty? then arr + other else arr + self end
+ end
+end