dynamic-programming(i): add day 1

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-01-19 18:23:35 +01:00
parent bf4f7c2ff5
commit 275d28ec33
No known key found for this signature in database
GPG key ID: 332171FADF1DB90B
2 changed files with 82 additions and 0 deletions

View file

@ -0,0 +1,39 @@
# @param {Integer} n
# @return {Integer}
def fib(n)
if n == 0 then
return 0
end
prev, current = 0, 1
(2..n).each {
prev, current = current, prev + current
}
return current
end
RSpec.describe "fib of " do
it "0 is 0" do
expect(fib(0)).to eq(0)
end
it "1 is 1" do
expect(fib(1)).to eq(1)
end
it "2 is 1" do
expect(fib(2)).to eq(1)
end
it "3 is 2" do
expect(fib(3)).to eq(2)
end
it "4 is 3" do
expect(fib(4)).to eq(3)
end
it "5 is 5" do
expect(fib(5)).to eq(5)
end
end

View file

@ -0,0 +1,43 @@
# @param {Integer} n
# @return {Integer}
def tribonacci(n)
sequence = [0, 1, 1]
if n < 3 then
return sequence[n]
end
(3..n).each {
sequence = sequence.drop(1) + [sequence.sum]
}
return sequence.last
end
RSpec.describe "tribonacci of " do
it "0 is 0" do
expect(tribonacci(0)).to eq(0)
end
it "1 is 1" do
expect(tribonacci(1)).to eq(1)
end
it "2 is 1" do
expect(tribonacci(2)).to eq(1)
end
it "3 is 2" do
expect(tribonacci(3)).to eq(2)
end
it "4 is 4" do
expect(tribonacci(4)).to eq(4)
end
it "5 is 7" do
expect(tribonacci(5)).to eq(7)
end
it "25 is 1389537" do
expect(tribonacci(25)).to eq(1389537)
end
end