Ruby Kata: Function To Generate A Tribonnaci Sequence Until n.


 
BY indefiniteloop


A Ruby kata to write a function that generates a Tribonacci series .

Problem Statement: Almost all of us are well aware of what a Fibonacci series is. This kata is based, instead, on a Tribonacci series. That is, we write a function to fum the last 3 (instead of the last 2) numbers of the sequence to generate the next number. You have to create a function that takes an array of 3 numbers as a signature, and returns a Tribonacci series, until ‘n’. If n=0 then we return an empty array.

It’s a really great, small rb kata that helps you think a little outside of the box. I didn’t even know there were other series; other than the Fibonacci.

Test Cases & Kata.

Ruby Kata: Function To Generate A Tribonnaci Sequence Until n.
Ruby Kata: Function To Generate A Tribonnaci Sequence Until n.

View Kata & Test Cases

Here’s How I Solved It

def tribonacci(signature,n)
  return Array.new if n<=0 
  return signature.take(n) if n<3
  (0..n-1).each do |x| signature << signature[x-3]+signature[x-2]+signature[x-1] if x>2 end
  return signature
end

Precise / Elegant Solution(s)

This one’s by abrae (and other people). ​

def tribonacci(s, n)
  for i in 3..n
    s[i] = s[i-1] + s[i-2] + s[i-3]
  end
  return s.slice(0, n)
end

Here’s another interesting solution by c0nspiracy

def tribonacci(signature, n)
  sequence = Enumerator.new do |y|
    loop do
      signature << signature.inject(:+)
      y << signature.shift
    end
  end
  sequence.take(n)
end

Tribonacci Series

Really a simple kata in ruby to play around with logic. Looking at the other solutions of this kata, it seems there are a lot of ways to solve this one. Great for learning, and thinking.

Solve This Kata




About The Author:

Home Full Bio