-
Notifications
You must be signed in to change notification settings - Fork 62
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #21 from augustojaba/augusto-baltazar-pr1
Issue #1: Add Fibonacci Dynamic Programming
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
/** | ||
* This is a algorithm to implement the Fibonacci Nth element problem | ||
* using dynamic programming paradigm. This version I am using the memoization | ||
* strategy to going top-down to find all needed values and store on the fiboMemo array. | ||
* | ||
* @author Augusto Baltazar ([email protected]) | ||
*/ | ||
public class Fibonacci { | ||
|
||
private int[] fiboMemo; | ||
|
||
private int findNthElement(int n) { | ||
|
||
if (this.fiboMemo == null) { | ||
fiboMemo = new int[n + 1]; | ||
} | ||
|
||
if (n <= 1) { | ||
fiboMemo[n] = n; | ||
} else { | ||
fiboMemo[n] = findNthElement(n - 1) + findNthElement(n - 2); | ||
} | ||
|
||
return fiboMemo[n]; | ||
} | ||
|
||
/** | ||
* Tests the function to the given number passed as argument | ||
* @param args | ||
*/ | ||
public static void main(String[] args) { | ||
try { | ||
int arg = Integer.parseInt(args[0]); | ||
System.out.println(new Fibonacci().findNthElement(arg)); | ||
} catch (Exception e) { | ||
System.out.println("The argument entered is not a valid integer number."); | ||
} | ||
} | ||
} |