r/ProgrammerHumor • • 3d ago

Meme dynamicProgramming

Post image
5.9k Upvotes

152 comments sorted by

View all comments

41

u/Illustrious-Ebb8815 3d ago edited 3d ago

A quick way to understand the difference is by looking at the program to compute Fibonacci numbers.

One way is just using recursion that runs in O(fib(n)) time. Like, the really really slow way.

Another way would be to use memorization. Just use the same recursive way but everytime that you're about to compute the answer, first check if the answer is in a cache that you have prepared. If yes, use that. If not, recurse. And when you get an answer, put it in the cache. That's memoization. It will run in O(n) time but also use O(n) space for the cache.

The algorithm that you probably know uses dynamic programming to run in O(n) time but constant space. That's DP.

You could also imagine using DP to compute the fewest number of coins to make x cents. If your biggest coin is 25 cents, you only ever need to know the answers for x-24 through x in order to compute the answer for x+1. This lets you solve the problem with linear time and constant storage, like with Fibonacci.

Edit: I meant memoization everywhere. Spell check messed it up.

21

u/PickMaleficent4096 3d ago

Fib(n) being used for DP has always been funny example to me. The naive recursive method is worse than the DP method sure... but if you calculate it the way a *human would on paper* it's the non-recursive O(n) time O(1) space solution.

5

u/suddencactus 3d ago

It's even funnier for me because analytic solutions exist.  We expect people to have complete mastery of courses in in discrete math and algorithms but then pretend they don't know how to use a generating series for a linear recurrence.

4

u/PickMaleficent4096 2d ago

To be honest I wouldn't expect anybody who isn't a specialist to be able to do that off the top of their head. The last time I heard the words "a generating series for a linear recurrence" was in college 10 years ago, and it hasn't been relevant to my software eng career since, including in interviews. I've had to dust off other parts of the math toolkit occasionally, but it's hard to justify analytical solutions in an environment where requirements are expected to change after your solution is live.

3

u/anonymity_is_bliss 3d ago

Exactly. All you need for O(n) are 3 variables.

The Rust version to go through all u64 Fibonacci values is just

fn main() {
    let mut a: u64 = 0;
    println!("{}", a);
    let mut b: u64 = 1;
    println!("{}", b);

    while let Some(c) = a.checked_add(b) {
        println!("{}", c);
        a = std::mem::replace(&mut b, c);
    }
    println!("Overflowed!");
}

5

u/Dork_Knight_Rises 3d ago

You don't need mem::replace for this, you can just use (a, b) = (b, c);

3

u/anonymity_is_bliss 3d ago

Shit, TIL that works in rust

1

u/-Redstoneboi- 1d ago

it wasn't always valid syntax, but they added support for it some time ago

1

u/suddencactus 3d ago

And with the prices of RAM these days we need all the O(1) space we can get.

1

u/-Redstoneboi- 1d ago

heh. there's also the O(log n) time O(1) space version.

or O(n) space if we're counting the expanding integer size.

18

u/-Redstoneboi- 3d ago

memoization should not have an r, btw. different spelling for whatever reason.

8

u/Illustrious-Ebb8815 3d ago

Spell check. 😔

4

u/SuitableDragonfly 3d ago

Memoization means using a memo to do a task. Memorization means committing something to memory, which is a thing that humans do, not computers. You don't say the computer is memorizing something because you stored it in RAM. They're spelled differently because they're based on two different roots. 

1

u/TommyBonnomi 3d ago

What if I use memory allocation in C or memory addresses in assembly?

Also, hard disks are secondary memory, so just saving something to disk.

→ More replies (2)

1

u/Jedkea 1d ago

I don’t think this is correct? I mean you literally store things in random access memory.

I take memoize to be a specific use case of memorization, wherein it’s used as a cache for expensive calculations.

I have never heard someone use memoize outside of this context, and would be pretty baffled if they did.

1

u/SuitableDragonfly 1d ago edited 1d ago

Yes, because a memo is a cache for partial solutions to calculations. That is literally what a memo is in computer science terms. Storing things in a computer's memory is not called "memorization" in any context. It refers to the human process of committing things to human memory, which is a lot more involved than just storing a piece of data somewhere.

1

u/-Redstoneboi- 1d ago

a parallel universe where the correct term is "memorization" is not so distant, considering how many typos have made it into the english language

see also: "sine" wave

1

u/SuitableDragonfly 1d ago

Not sure what you mean. Sine is from Latin sinus and follows standard patterns for how things were borrowed from Latin into English.

→ More replies (6)
→ More replies (1)

4

u/Darkstar_111 3d ago

There has to be a better abbreviation...

1

u/Xywzel 3d ago

Another way would be to use memorization. Just use the same recursive way but everytime that you're about to compute the answer, first check if the answer is in a cache that you have prepared. If yes, use that. If not, recurse. And when you get an answer, put it in the cache. That's memoization. It will run in O(n) time but also use O(n) space for the cache.

Doesn't this ignore cache update and lookup times? I guess O(n_max) (n->infinity makes that hard) would have plain array indexed with n, but otherwise you end with at least multiples of n. And there is a loop or tail recursion that has O(n) time and constant memory use anyway. Point of memoization is that after first time, its cache fetch complexity rather than original complexity, O(1) if we have enough memory and trivial index, and you can do that with the loop and tail recursion as well.

1

u/rnottaken 3d ago

You only need a cache of size 2 i believe

1

u/donaldhobson 3d ago
def fib(i):
    a,b,c=0,1,1
    for j in bin(i)[3:]:
        a,b,c=a*a+b*b,(a+c)*b,b*b+c*c
        if j=="1":
            a,b,c=b,c,b+c
    return c

Fast Fibonacci algorithm. O(log(j)) if you ignore that * isn't constant time.

1

u/Lithl 2d ago
const root5 = Math.sqrt(5);
const phi = (1 + root5) / 2;
const psi = (1 - root5) / 2;

function fib(n) {
    return (Math.pow(phi, n) - Math.pow(psi, n)) / root5;
}

Closed-form Fibonacci expression. O(1) if you ignore that exponentiation isn't constant time.

→ More replies (1)
→ More replies (6)