✅ Fibonacci sequence
Im trying to learn dynamic programming and im struggling to understand the bottom up approach for the fibonacci sequence problem. I watched a couple of videos on this topic but all of the code in them is written in other languages. It would be great if someone wrote the method in c# so i could understand it better. Thank you in advance!
12 Replies
blueberriesiftheywerecats
REPL Result: Success
Console Output
Compile: 389.877ms | Execution: 86.404ms | React with ❌ to remove this embed.
while the first code snippet is right(and even sorta optimal)...that's a pretty bad way to explain the point of memoization
Memoization exists for situations where there is redundant calculations being done.
for example here,
If i used
nth_number
as something like 5, it'd start off as a call to Fib(5)
, then
Fib(5)
calls (case a)Fib(4)
and Fib(3)
for case a:
Fib(4)
calls Fib(3)
and Fib(2)
Fib(3)
calls Fib(2)
and Fib(1)
, then Fib(2)
calls Fib(1)
and Fib(0)
--ends here
Fib(2)
(from the Fib(4)
call) is done again (an example of a redundant call as Fib(2)
was already done)
for something like Fibonacci it wouldn't matter too much to have redundant calls, but for situations similar in nature to it with stuff like expensive calculations in each function call, it pays to have redundant calls.
That's where memoization comes in, it caches(stores) each call once completed so that if this call were to happen again it would not need to do the expensive calculations again, it just returns the cached call.
A way to properly implement memoization in Fibonacci would be
i think this is also top-down approach...i am not 100% sure but that should be the term, for bottom-up approach instead of doing recusively + using caching you'd just do it completely iteratively
like with a loop
it may be <=
instead of <
but i am not on vscode and im too stupid to do it in my head
okay it is <
that's how it is done bottom-upTHANK YOU! im gonna read everything and see if i understand it all
isnt this topdown approach better? the dictionary is outside of the methods so it stores the values even if the method is called again
i used that instead of the declaring the dict in the method because i was testing it like this:
yeah i could have made the array outside the method and put it as a class field. That is actually my preferred way to do stuff like this cus it makes it clearer for me
also, do you think the fib sequence is 0 1 1 2.. or 0 1 2 ?
or something else
1 1 2..
it's 0, 1 as the first two numbers
then it starts
next number 0 + 1
and continue
right
this is supposed to be n<=3 btw,
this is supposed to be n<=3 btw
and here why not use a for loop instead of while and count variable
oh
actually
yeah why didn't i
great question, a for-loop is better
i just did NOT think of it
ok well thank you
you helped a lot
if i close this thread will this it be deleted?
honestly I'm not sure