Recursive Function into Non-Recursive Function? - recursion

I have the following recursive Grails function:
private boolean isCyclic(TreeNode node) {
boolean cyclic = false
def myParents = this.parents
// if there are parents of this node
if (myParents.size() != 0) {
// if the new node is in the parents set of this node
if (myParents.contains(node)) {
cyclic = true
return cyclic
}
else {
// go into each parent of this node and test if new node is contained in their parents
myParents.each { parent ->
log.debug "go to parent: "+parent.name
if (cyclic) {
return cyclic
}
cyclic = parent.isCyclic(node)
}
}
}
return cyclic
}
How can I transform this function into a non-recursive function?

I think your code above is a contains method, rather than a cyclic check...
However here's a quick example of both a contains method and a cyclic check in an iterative style... Fingers crossed they're right
def contains( TreeNode node ) {
// if this node is the one we're looking for, return true
if( node == this ) {
return true
}
// A queue of nodes to work on
def parentQueue = this.parents as Queue
// A set of nodes we've seen (to avoid loops)
def seen = [ this ] as Set
// While we have nodes to look for
while( parentQueue ) {
// get the next node
def next = parentQueue.pop()
// Check if it's the one we're looking for
if( next == node ) return true
// And if not, add it's parents to the queue
// assuming we've not seen it before
if( !seen.contains( next ) ) {
next.parents.each { parentQueue.offer( it ) }
}
}
// Not found
return false
}
def isCyclic() {
// A queue of nodes to work on
def parentQueue = this.parents as Queue
// A set of nodes we've seen (to detect loops)
def seen = [ this ] as Set
// While we have nodes to look for
while( parentQueue ) {
// Look at the next element in the queue
def next = parentQueue.pop()
// If we've seen it before, it's cyclic
if( seen.contains( next ) ) return true
// Otherwise, record we've seen this node
seen << next
// And add its parents tothe queue
next.parents.each { parentQueue.offer( it ) }
}
// All done, not cyclic
return false
}

Tom Moertel wrote solution for this problem on his blog.
He clearly explained the transformation of recursive function into the iterative (link).
I have used his approach to transform my own functions when I needed and I was convinced that is correct.
I hope that helps.

Basically to transform a recursive function into an iterative function you should notice which is the case base(this case is the stop case of recursive function), put all functionality into a loop and use that base case as exit condition of used loop.
Perhaps i didn't explain it very well but every recursive function has an iterative function.

Related

How can I get out of this infinite loop?

I am writing a recursive function to find the index of a node in a linked list. It looks like this:
function indexAt(node, collection, linkedList) {
let index = 0;
if (node === nodeAt(index, linkedList,collection)) {
return index
} else {
index ++
return indexAt(node, collection, linkedList)
}
}
It calls on the nodeAt function, which looks like this:
function nodeAt(index, linkedList, collection) {
let node = collection[linkedList];
for (let i=0; i < index; i++) {
node = next(node, collection)
}
return node
}
This works fine when the index is 0, but when it is anything else, it increments the index, then sets it back to 0, entering an infinite loop. How can I fix this without fundamentally altering the code?
Well at the start of the function you reset the index to 0. So every time it recurs, it resets the index, thus causing your infinite loop.
An easy fix is to declare the index variable outside the function. That will ensure it's not reset every time the function recurs.
A better fix would be to pass the index as an argument to the function so that it will always keep track of its own index.
Just make a helper that holds the extra variable:
function indexAt(node, collection, linkedList) {
function indexAt(index, node, collection, linkedList) {
if (node === nodeAt(index, linkedList, collection)) {
return index
} else {
return indexAt(index + 1, node, collection, linkedList)
}
}
return indexAt(0, node, collection, linkedList);
}
Now you count from 0...n and make nodeAt start at the beginning each time making this O(n^2). A much better way would be that the helper has the current node, initialized at collection[linkedList] and stepping with next(currentNode) and index + 1 until node === currentNode. That would be a O(n) solution. indexAt doesn't really need to be recursive unless it is a requirement.

Not understood return behavior of recursive function with closure

The foundations of my programming "skills" are shaking.. I don't know if this behavior is caused by the recursion, closure or something else, but this is by far the weirdest thing I've seen so far.
My original intention was to use recursion to count the parents of dom element. The closure is implemented to store my counter and recursion would increase it for every parent that is not equal to div#wrapper. And it works - once. For the first element (having only 1 parent - it returns 1) However the second time it returns undefined. for the sake of testing I came up with this rig:
let parents = countParents();
let pathLength = parents(3);
function countParents() {
let counter = 0;
return function nextParent(node) {
let parent = node - 1;
counter++;
if (parent === 1)
return 'WATAFAK';
else
nextParent(parent);
}
}
console.log(pathLength);
I am actually questioning my eyes (it's late, been programming for a while now), but this function returns undefined. HOW is that possible?
function countParents() {
let counter = 0;
return function nextParent(node) {
let parent = node - 1;
counter++;
if (parent === 1)
return 'WATAFAK';
else
nextParent(parent); // call nextParent(parent) and throw away result
return undefined; // invisible line in every function
}
return undefined; // invisible line in every function (never reached)
}
If you wanted the result of the recursion to be the result you must add return in front of it. How it is now it's only for side effects and it's pretty much dead code.
Since the else branch doesn't return all functions have a invisible return undefined, just before its block ends.

how stacks are formed and value from a method return when the method has TWO recursive calls of itself from within itself

I have tried creating stacks for recursive inorder,preorder,postoreder traversal for binary tree and I was doing it pretty well. In other cases like, for example, for a test case my answer should be 'true',say.And, for example,
boolean method(root)
{
// more code
method(root.left());
method(root.right());
}
,somewhere,the call of method(root.left()) returns false and a call of method(root.right()) returns true that should be our answer. But since call of method(root.left() ) completes first and somewhere, in between it's execution, it might have returned false. then how do we get our result true from method(root.right())?? I think it is related to how stacks are formed and values from a method are returned when recursive calls ,in this way, happen.Explain it and correct me if I am wrong.
You need to return values. The method need to make use of the returned values in its logic to stop/continue the search.
You need to have that the base cases return either true of false. Then when doing the first recursive call you need only do the first if the result is true. The second recursive call would be the result of the method if it's needed. Thus you are looking at something like this:
boolean method(root)
{
if( root == null ) { // base case 1
return false;
}
if( root.value == someValue ) { // base case 2, what should be a positive
return true;
}
// default search left first and return true if true
if( method(root.left()) ) {
return true;
}
// default search right and return true if true
if( method(root.right()) ){
return true;
}
// return false since neither recursive calls were true
return false;
}
This is very verbose and can be written like this instead:
boolean method(root)
{
return root != null && ( root.value == someValue ||
method(root.left()) ||
method(root.right()));
}
I find the last more readable but novices might find the more verbose first one to be more clear.
In both the callee resumes operation after the first recursive call (which might have had it's share of calls as well) and continues it's logic and recurses on the right side if needed.
Don't care about the system stack. Care about the base case and test them. Then do the simplest of added complexity to do the default case so that you see the problem becoming smaller in the recursive call(s). It's much better going from simple to more complex than to try figuring this stuff out by starting at a large tree looking at whats happening with a very deep recursive round.

how to follow a recursive isBST function?

I'm trying to follow a specific implementation of a recursive (in-order traversal) isBST function.
I tried to simulate it with the simple invalid BST example:
root=5, root.left=3, root.left.right=8
5
/
3
\
8
i'm getting either 'true' or 'false' but without having to check the last node '8'.
the code is as follows:
/* wrapper that keeps track of the previous value */
class PrevWrapper {
int data = Integer.MIN_VALUE;
}
boolean isBST(Node root, PrevWrapper prev) {
/* base case: we reached null*/
if (root == null) {
return true;
}
if(!isBST(root.left, prev)) {
return false;
}
/* If previous in-order node's data is larger than
* current node's data, BST property is violated */
if (prev.data > root.data) {
return false;
}
/* set the previous in-order data to the current node's data*/
prev.data = root.data;
return isBST(root.right, prev);
}
boolean isBST(Node root) {
return isBST(root, new PrevWrapper());
}
what is the correct order of returning the recursive calls?
EDIT:
I was thinking:
(#)isBST(5,min), isBST(3,min), isBST(3.left=null,min) - returns true, skips to prev=3, isBST(8,3), isBST(8.left=null,3) - returns true, skips to prev=8, isBST(8.right=null,8) - returns true to (#), checks 8 > 5? returns false.
I think I got it, is this the correct order of calls?
thanks in advance.

Newbie on use of recursion in Groovy/traverse tree?

In our current application we have a need to traverse down a tree and capture all operators on a specific device (and child devices). A device could have child devices with also specific operators on it.
As i am new to the use of recursion in Groovy i am wondering if i am doing things right..?
Any pointer to help me learn better ways of doing things?
def listOperators(device) {
// list with all operator id's
def results = []
// closure to traverse down the tree
def getAllOperators = { aDevice->
if(aDevice) {
aDevice.operators.each { it ->
results << it.id
}
}
if (aDevice?.children) {
aDevice.children.each { child ->
results << owner.call(child)
}
}
}
// call the closure with the given device
getAllOperators(device)
// return list with unique results
return results.unique()
}
A couple things to note:
Doing the recursive call through owner is not a good idea. The definition of owner changes if the call is nested within another closure. It's error prone and has no advantages over just using the name. When the closure is a local variable, split its up the declaration and definition of the closure so the name is in scope. E.g.:
def getAllOperators
getAllOperators = { ...
You are appending the operators to a result list outside the recursive closure. But you are also appending the result of each recursive call to the same list. Either append to the list or store the results from each recursive call, but not both.
Here's a simpler alternative:
def listOperators(device) {
def results = []
if (device) {
results += device.operators*.id
device.children?.each { child ->
results += listOperators(child)
}
}
results.unique()
}

Resources