RosettaCodeData/Task/Generator-Exponential/Ruby/generator-exponential-2.rb

24 lines
538 B
Ruby
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
# This solution uses three generators.
def powers(m)
2015-02-20 00:35:01 -05:00
return enum_for(__method__, m) unless block_given?
2016-12-05 22:15:40 +01:00
0.step{|n| yield n**m}
2013-04-10 21:29:02 -07:00
end
def squares_without_cubes
2015-02-20 00:35:01 -05:00
return enum_for(__method__) unless block_given?
2013-04-10 21:29:02 -07:00
2016-12-05 22:15:40 +01:00
cubes = powers(3) #no block, so this is the first generator
2013-04-10 21:29:02 -07:00
c = cubes.next
2016-12-05 22:15:40 +01:00
squares = powers(2) # second generator
2013-04-10 21:29:02 -07:00
loop do
s = squares.next
2015-02-20 00:35:01 -05:00
c = cubes.next while c < s
2013-04-10 21:29:02 -07:00
yield s unless c == s
end
end
2016-12-05 22:15:40 +01:00
answer = squares_without_cubes # third generator
2013-04-10 21:29:02 -07:00
20.times { answer.next }
2015-02-20 00:35:01 -05:00
p 10.times.map { answer.next }