Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.09 KB | None | 0 0
  1. // Coded calculation of Fibonacci sequence with memoization using a HashMap as data structure
  2.  
  3. import java.sql.Timestamp;
  4. import java.util.HashMap;
  5.  
  6. public class FibMemoization {
  7.     private static HashMap<Integer, Integer> results;
  8.    
  9.     private static void log(String message) {
  10.         System.out.println(new Timestamp(System.currentTimeMillis()) + ": " + message);
  11.     }
  12.    
  13.     private static int fib(int n) {
  14.         if (n == 0) return 0;
  15.         if (n == 1) return 1;
  16.        
  17.         // Lookup HashMap
  18.         if (results.containsKey(n)) {
  19.             return results.get(n);
  20.         }
  21.        
  22.         // Calculate value
  23.         log("Calculating fib(" + n + ")");
  24.         int ans = fib(n - 1) + fib(n - 2);
  25.         log("Calculated fib(" + n + ")");
  26.        
  27.         // Store in HashMap
  28.         results.put(n, ans);
  29.        
  30.         return ans;
  31.     }
  32.    
  33.     public static void main(String[] args) throws Exception {
  34.         if (args.length == 0) {
  35.             log("Please enter an integer argument");
  36.             throw new Exception("Please enter an integer argument");
  37.         }
  38.        
  39.         log("Will calculate fib(" + args[0] + ")");
  40.         results = new HashMap<Integer, Integer>();
  41.         log("Answer is: " + fib(Integer.parseInt(args[0])));
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement