Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Coded calculation of Fibonacci sequence with memoization using a HashMap as data structure
- import java.sql.Timestamp;
- import java.util.HashMap;
- public class FibMemoization {
- private static HashMap<Integer, Integer> results;
- private static void log(String message) {
- System.out.println(new Timestamp(System.currentTimeMillis()) + ": " + message);
- }
- private static int fib(int n) {
- if (n == 0) return 0;
- if (n == 1) return 1;
- // Lookup HashMap
- if (results.containsKey(n)) {
- return results.get(n);
- }
- // Calculate value
- log("Calculating fib(" + n + ")");
- int ans = fib(n - 1) + fib(n - 2);
- log("Calculated fib(" + n + ")");
- // Store in HashMap
- results.put(n, ans);
- return ans;
- }
- public static void main(String[] args) throws Exception {
- if (args.length == 0) {
- log("Please enter an integer argument");
- throw new Exception("Please enter an integer argument");
- }
- log("Will calculate fib(" + args[0] + ")");
- results = new HashMap<Integer, Integer>();
- log("Answer is: " + fib(Integer.parseInt(args[0])));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement