Rafeh Ishtiaq
Rafeh Ishtiaq

Reputation: 113

Recursive sequence of integers

I want to generate a sequence of integers using recursion. If I enter 2, the o/p should be [2, 6, 22, 86, 342]. I want to achieve this by using a recursive function. I have done the following using iteration:

n = gets
i = 0
a = Array.new
a.push(n)
while i < 4
  n = n * 4 - 2
  a.push(n)
  i = i + 1
end
p a

What changes should be made?

Upvotes: 0

Views: 96

Answers (2)

iGian
iGian

Reputation: 11193

Other option:

def sequence(n, res=[])
  return res if res.size == 5
  sequence(n*4-2, res << n)
end

Upvotes: -1

engineersmnky
engineersmnky

Reputation: 29478

This should do it for you:

def seq(num,limit=5) 
  return [] if limit < 1
  [num] + seq(num*4-2,limit - 1)
end

Then

seq(2,5)
#=> [2, 6, 22, 86, 342]

I would add some kind of an explanation but I am not really sure what to say. This is a recursive version of your proposed methodology.

We could also make this an Enumerator like so

enum= ->(num) { Enumerator.new do |y|
                  loop do 
                    y << num 
                    num = num*4-2
                  end
                end } 
seq = enum.(2)
seq.take(7)
#=> [2, 6, 22, 86, 342, 1366, 5462]
enum.(3).take(4)
#=> [3, 10, 38, 150]

Not exactly recursive per se but it is a common practice for building a number generator that can be reused.

Upvotes: 3

Related Questions