On 12/4/05, James Edward Gray II <james / grayproductions.net> wrote:
>
> NOW you're talking!  You could just calculate them once and that's
> the best of both worlds...  ;)

Well I coded this up. Instead of pasting my whole solution I'll just
paste the cache class and the updated "main" block for my solution.
I've also added some timing code so one can see the speed
improvements. To try this out, replace my if $0 == __FILE__ code from
my original solution with all of the following:

class WeirdCache
  def initialize(filename='.weirdcache')
    @filename = filename
    if test(?e, filename)
      @numbers = IO.readlines(filename).map do |i|
        i.chomp.to_i
      end
    else
      @numbers=[]
    end
    @added = false
  end

  def each(&block)
    @numbers.each(&block)
  end

  def <<(i)
    @added = true
    @numbers << i
  end

  def save
    if @added
      File.open(@filename, File::RDWR|File::CREAT|File::TRUNC) do |file|
        file.puts @numbers
      end
    end
  end
end

if $0 == __FILE__
  if ARGV.length < 1
    puts "Usage: #$0 <upper limit>"
    exit(1)
  end

  puts "Weird numbers up to and including #{ARGV[0]}:"
  start = Time.now
  cache = WeirdCache.new
  at_exit {cache.save}
  limit = ARGV[0].to_i
  i = 69
  cache.each do |i|
    if i <= limit
      puts i
    end
  end
  (i+1).upto(limit) do |j|
    if j.weird?
      cache << j
      puts j
    end
  end
  puts "This took #{Time.now - start} seconds"
end