Владимир обнови решението на 23.10.2015 16:40 (преди над 9 години)
+class RationalSequence
+
+ include Enumerable
+
+ def initialize(limit)
+ @limit = limit
+ end
+
+ def each(&block)
+ numerator, denominator, direction, yielded = 1, 1, nil, []
+ while yielded.size < @limit
+ unless yielded.include? (rational = Rational(numerator, denominator))
+ yielded << rational and yield rational
+ end
+ if (numerator == 1 && denominator == 1) || (numerator.odd? && denominator == 1)
+ numerator += 1
+ elsif numerator == 1 && denominator.even?
+ denominator += 1
+ elsif (numerator.even? && denominator == 1)
+ direction = 'up' and denominator += 1 and numerator -= 1
+ elsif direction == 'down' || (numerator == 1 && denominator.odd?)
+ direction = 'down' and denominator -= 1 and numerator += 1
+ elsif direction == 'up'
+ denominator += 1 and numerator -= 1
+ end
+ end
+ end
+end
+
+class FibonacciSequence
+
+ include Enumerable
+
+ def initialize(limit, first: 1, second: 1)
+ @limit = limit
+ @first = first
+ @second = second
+ end
+
+ def each(&block)
+ (1..@limit).each do |index|
+ yield nth(index)
+ end
+ end
+
+ def nth(n)
+ return @first if n <= 1
+ return @second if n == 2
+ nth(n-1) + nth(n-2)
+ end
+
+end
+
+class Numeric
+
+ def prime?
+ return false if self == 1
+ (2..self/2).none?{|i| self % i == 0} ? true : false
+ end
+end
+
+class PrimeSequence
+
+ include Enumerable
+
+ def initialize(limit)
+ @limit = limit
+ end
+
+ def each(&block)
+ yielded = 0
+ (2..Float::INFINITY).each do |number|
+ break if yielded == @limit
+ if number.prime?
+ yielded += 1
+ yield number
+ end
+ end
+ end
+end
+
+class DrunkenMathematician
+
+ class << self
+
+ def meaningless(n)
+ rationals = RationalSequence.new(n).to_a.partition do |rational|
+ (rational.numerator.prime? || rational.denominator.prime?)
+ end
+ rationals.map { |group| (group.reduce(:*) || Rational(1, 1)) }.reduce(:/)
+ end
+
+ def aimless(n)
+ rationals = []
+ primes = PrimeSequence.new(n).to_a
+ primes.each_slice(2) do |numerator, denominator|
+ rationals << Rational(numerator, (denominator || 1))
+ end
+ rationals.reduce(:+)
+ end
+
+ def worthless(n)
+ fib = FibonacciSequence.new(n).to_a.last
+ result = []
+ n.downto(1) do |current|
+ result = RationalSequence.new(current).to_a
+ break if result.reduce(:+).to_i <= fib
+ end
+ result
+ end
+ end
+end