bragboy
bragboy

Reputation: 35542

Need help with loops

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.......

Upvotes: 1

Views: 193

Answers (5)

Cary Swoveland
Cary Swoveland

Reputation: 110665

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

Upvotes: 0

Nakilon
Nakilon

Reputation: 35064

i = 1
loop do
    for j in 0...i
        puts i+j
    end
    i *= 10
end

Upvotes: 1

AboutRuby
AboutRuby

Reputation: 8116

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

Upvotes: 0

sepp2k
sepp2k

Reputation: 370102

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]

Upvotes: 5

Chubas
Chubas

Reputation: 18043

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.

Upvotes: 2

Related Questions