Count number of ways to cover a distance | A Dynamic Programming based javascript program to count number of ways ; Create the array of size 3. ; Initialize the bases cases ; Run a loop from 3 to n Bottom up approach to fill the array ; driver code
function printCountDP ( dist ) { var ways = [ ] , n = dist ; ways . length = 3 ; ways [ 0 ] = 1 ; ways [ 1 ] = 1 ; ways [ 2 ] = 2 ; for ( var i = 3 ; i <= n ; i ++ ) ways [ i % 3 ] = ways [ ( i - 1 ) % 3 ] + ways [ ( i - 2 ) % 3 ] + ways [ ( i - 3 ) % 3 ] ; return ways [ n % 3 ] ; } var dist = 4 ; document . write ( printCountDP ( dist ) ) ;