jsc42
jsc42

Reputation: 117

(Ruby) First x Recursive Nums

I want to write a recursive method that returns the first num recursive numbers.

Here is my code so far:

def recursive_factorials(num)
  return [1] if num == 1
  arr = recursive_factorials(num-1)
  arr << num * arr.last
end

Not sure what I'm doing wrong. The expected result for num = 6 is [1, 1, 2, 6, 24, 120], and I get [1, 2, 6, 24, 120, 720], so I may be close but really have no idea.

Any help would be appreciated. Also, if I am not using recursion properly please let me out.

Upvotes: 2

Views: 82

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Here is an example:

def recursive_factorials(num, acc = [])
  acc << (num < 2 ? 1 : (num - 1) * recursive_factorials(num - 1, acc).last)
end
recursive_factorials 6
#⇒ [1, 1, 2, 6, 24, 120]

Upvotes: 2

Ilya
Ilya

Reputation: 13487

Question is about recursion, but also you can use iteration, it's faster:

def factorials(num)
  m = 1
  (0...num).map {|e| e.zero? ? 1 : m *= e }
end
factorials(6)
=> [1, 1, 2, 6, 24, 120]

Or by using hash memoisation (I would say its a recursion too):

factorials = Hash.new { |h, k| h[k] = h[k-1] * k }.update(0 => 1)
factorials.values_at(*(0..5))
=> [1, 1, 2, 6, 24, 120]

Upvotes: 2

Stefan
Stefan

Reputation: 114208

A variation of Ilya's answer:

def each_factorial
  return enum_for(__method__) unless block_given?
  m = 1
  1.step do |i|
    yield m
    m *= i
  end
end

each_factorial.take(6)
#=> [1, 1, 2, 6, 24, 120]

Upvotes: 1

Related Questions