c# - Rewrite Recursive algorithm more simply - Euler 15 -


i rewrite functionality of algorithm (which used solve projecteuler problem 15) in non recursive way.

yes, realise there many better ways solve actual problem, challenge simplify logic as possible.

public class solverecursion {     public long combination = 0;     public int gridsize;      public void calculatecombination(int x = 0, int y = 0)     {         if (x < gridsize)         {             calculatecombination(x + 1, y);         }         if (y < gridsize)         {             calculatecombination(x, y + 1);         }         if (x == gridsize && y == gridsize)             combination++;     } } 

and tests:

[test] public void solverecursion_giventhree_givesanswerof20routes() {     solverecursion.gridsize = 3;     solverecursion.calculatecombination();     var result = solverecursion.combination;     assert.areequal(20, result); }  [test] public void solverecursion_givenfour_givesanswerof70routes() {     solverecursion.gridsize = 4;     solverecursion.calculatecombination();     var result = solverecursion.combination;     assert.areequal(70, result); } 

edit: here simple function written in both ways:

//recursion private int factorial(int number) {     if (number == 0)         return 1;     int returnedvalue = factorial(number - 1);      int result = number*returnedvalue;     return result; }  //loop private int factorialasloop(int number) {     //4*3*2*1     (int = number-1; >= 1; i--)     {         number = number*i;     }     return number; } 

any hints appreciated. i've tried dynamic programming solution (which uses more maths based approach), , equation solve puzzle.

i wonder - can first algorithm made non recursive, simply?

the non-recursive solution is:

const int n = 4; int a[n + 2][n + 2] = {0};  a[0][0] = 1; (int = 0; < n + 1; ++i)     (int j = 0; j < n + 1; ++j) {         a[i][j + 1] += a[i][j];         a[i + 1][j] += a[i][j];     }  std::cout << a[n][n] << std::endl; 

just information, problem should have been solved on paper, answer nxm grid c(n+m,n), c combination function - http://en.wikipedia.org/wiki/combination


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -