c++ - Writing Recursive code iteratively -


i have following recursive code want change iterative code. unsure of begin function complex recursive calls @ 2 locations. possible iterative implementations below function ?

int ncip(int dim, double r){     int n, r = (int)floor(r);      if (dim == 1)         return 1 + 2*r;      n = ncip(dim-1, r); // last coord 0      (int i=1; i<=r; ++i){         n += 2*ncip(dim-1, sqrt(r*r - i*i) ); // last coord +-     }      return n; } 

one common approach use stack function calls. simple implementation follows , can optimization on it

int ncip(int dim, double r){     typedef pair<int, double> data; // ties parameters 1 unit      stack<data> s;     s.push(make_pair(dim,r)); // push first set of parameters     int n = 0;      while(false == s.empty()) { // loop until stack depleted         auto item = s.top(); // top item , pop after         s.pop();         int r = static_cast<int>(floor(item.second));          if (item.first == 1) {             n += 1 + 2*r;          } else {             s.push(make_pair(item.first-1,item.second));              (int = 1; <= r; ++i){                 // since have multiplier 2 push same parameters twice                 s.push(make_pair(item.first-1, sqrt(item.second*item.second - i*i) ));                 s.push(make_pair(item.first-1, sqrt(item.second*item.second - i*i) ));             }         }     }     return n; } 

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -