☕ Exercise solutions for chapter 1.1 written in Java
- isBetweenZeroAndOne()
- toBinaryString()
- printTwoDmBooleanArray()
- printTwoDmIntArray()
- printIntArray()
- matrixTransposition()
- lg()
- Fibonacci.Fib()
- Fibonnaci.FastFib()
- fact()
- binarySearch()
- bruteForceSearch()
We are asked in exercise (1.1.19) to improve the fib method to use some sort of cache. This one is particularly interesting because it runs in O(1) time provided that the cache contains the previous two sequences. Generating the previous sequences is done using loops.
// dynamic programming and memoization
public static long FastFib(int N, HashMap<Integer, Long> cache) {
if (N == 0) {
cache.put(N, 0L);
return 0;
}
if (N == 1) {
cache.put(N, 1L);
return 1;
}
cache.put(N, cache.get(N - 2) + cache.get(N - 1));
return cache.get(N);
}
I've implemented the same methods but in Python over here, if you're interested.