Hi!
I want to use a recursive function f, which creates the optimal solutions for a problem. Just to be clear, number of optimal solutions is not the number of recursions of the function, but much much less than that. I want to have a counter variable to display the indices of the optimal solutions of the problem.
By far what I have done is that I created a counter globally (using <<-). This works perfectly. But now I have been recommended by our professor to avoid it, if possible.
I came across the R function new.env and it gives me the idea of creating another function g. I will then create an environment under it and define the counter there. Then I will call f and use the counter as I did before.
But I am not really getting how to do it. Any ideas/suggestions/hints?
I know it helps to have a reproducible example, but I can't really provide one.
What I have done is somewhat similar to the following:
# recursive function - function of interest
g <- function(arguments)
{
if(condition)
{
...
g(arguments)
} else
{
cat("Solution No.", counter)
print(solution)
counter <<- counter + 1
}
}
# parent function - under which counter will be defined
f <- function(arguments)
{
counter <<- 1
g(arguments)
}
And what I want is this:
# parent function - under which counter will be defined
f <- function(arguments)
{
# create a new environment, say e
# initialize counter in e as 1
g(arguments)
}
# recursive function - function of interest
g <- function(arguments)
{
if(condition)
{
...
g(arguments)
} else
{
# cat("Solution No.", counter as in e)
print(solution)
# update counter by incrementing it by 1
}
}
Any help will be appreciated.