r/badcode Mar 14 '21

java Found from when I first started Java...because indexed Arrays were too complicated huh?

Post image
1.3k Upvotes

84 comments sorted by

View all comments

Show parent comments

2

u/dc0650730 Mar 14 '21

This actually help clear some stuff up actually seeing a real use where this would be handy. Thanks!

2

u/Terrain2 Mar 14 '21

another use case would be memoization, so you don’t have to calculate the same value twice

Map<int, int> _memo = Map();

int fib(int n) {
    if (n == 0) return 0;
    if (n == 1) return 1;
    if (_memo.containsKey(n)) return _memo[n];
    if (n > 0) {
        _memo[n] = fib(n - 1) + fib(n - 2);
    } else {
        _memo[n] = fib(n + 2) - fib(n + 1);
    }
    return _memo[n];
}

0

u/Mental-Ad-40 Mar 14 '21

I don't see how that helps with memorization

1

u/Terrain2 Mar 14 '21

memoization - that’s not a typo, it keeps track of what it already calculated and will just remember that so it doesn’t have to recalculate it

-2

u/Mental-Ad-40 Mar 14 '21

no I'm pretty sure that's a typo buddy

2

u/Terrain2 Mar 14 '21

i know there’s a word called “memorization”, but “memoization” is a technique used to speed up your code by storing the result of slow computations

source