Hi,
I need a loop in this pattern. I need an infinite loop producing number that start with 1.
1,10,11,12..19,100,101,102..199,1000,1001.......
Hi,
I need a loop in this pattern. I need an infinite loop producing number that start with 1.
1,10,11,12..19,100,101,102..199,1000,1001.......
INFINITY = 1.0 / 0.0
0.upto(INFINITY) do |i|
((10**i)...(2*10**i)).each{|e| puts e }
end
Of course, I wouldn't run this code.
def numbers_that_start_with_1
return enum_for(:numbers_that_start_with_1) unless block_given?
infty = 1.0 / 0.0
(0..infty).each do |i|
(0 .. 10**i - 1).each do |j|
yield(10**i + j)
end
end
end
numbers_that_start_with_1.first(20)
#=> [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 100, 101, 102, 103, 104, 105, 106, 107, 108]
Enumerators are good for things like this. Though, I was lazy and just decided to see if the string representation starts with 1, and iterate through 1 at a time. This means it'll be slow, and it'll have huge pauses while it jumps from things like 1,999,999 to 10,000,000.
#!/usr/bin/env ruby
start_with_1 = Enumerator.new do|y|
number = 1
loop do
while number.to_s[0] != '1'
number += 1
end
y.yield number
number += 1
end
end
start_with_1.each do|n|
puts n
end
Not better, just different...
def nbrs_starting_with_one(nbr=1)
(nbr...2*nbr).each {|i| puts i}
nbrs_starting_with_one(10*nbr)
end