Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sequence from specific number?

Tags:

ruby

How to make sequence from the beginning of square number and then adding it to the previous result?

7 => 49, 56, 63, ...

def make_sequence(number)
  lambda { number*number ??? }
end

num = make_sequence(7)
num.call #=> 49
num.call #=> 56
...
like image 403
megas Avatar asked May 15 '26 22:05

megas


2 Answers

Following your initial idea using closures I'd write:

def make_sequence(n)
  x = n**2 - n
  lambda { x += n }
end

num = make_sequence(7)
p num.call #=> 49
p num.call #=> 56
like image 197
tokland Avatar answered May 19 '26 04:05

tokland


use Enumerator

def make_sequence(start)
  pos = start**2
  Enumerator.new do |y|
    loop do
      y.yield(pos)
      pos += start
    end
  end
end

seq = make_sequence(7)
seq.next   #=> 49
seq.next   #=> 56

...
like image 39
levinalex Avatar answered May 19 '26 04:05

levinalex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!