问题描述
为了更好地了解R并了解递归的工作原理,我实现了递归除法迷宫生成算法。 据我所知,我的实现有效,但仅当我使用超级分配运算符“
因此,对于return()函数和环境的工作方式,我显然缺少一些东西,但是我无法弄清楚这是什么,或者如何在无需使用全局赋值的情况下使代码工作。 我也不确定如何缩小该示例的大小,因为我从未遇到过这样的问题,因此对冗长的代码表示抱歉。
这是有效的代码:
N = 10 # extent x & y
fin = 2 # finish recursion
maze = array(1,dim = c(N,N))
divide <- function(grid,width,height,fin,xoff = 0,yoff = 0){
set.seed(123)
# end recursion
if (width <= fin || height <= fin){
maze <<- grid #this is the part i want to get rid of
return(grid)
}
# choose if vertical or horizontal wall
if (width < height){ orient = 2 } #horizontal
else if (height < width ){ orient = 1 } # vertical
else { orient = sample.int(2,1,TRUE) }
# build wall with a passage in it
if (orient == 2){
wall <- 2L * sample.int((height-1)/2,TRUE)
pass <- 2L * sample.int(width/2,TRUE) -1
build <- 1:width
build <- build[-pass] + xoff
grid[wall + yoff,build] <- 0
}else {
wall <- 2L * sample.int((width-1)/2,TRUE)
pass <- 2L * sample.int(height/2,TRUE)-1
build <- 1:height
build <- build[-pass] + yoff
grid[build,wall + xoff] <- 0
}
# this is just for plotting,so that the image faces the right direction
pic <- apply(grid,2,rev)
image(t(pic))
Sys.sleep(1.5)
# recusion in the sub areas
if (orient == 2)
{
# Top & Bottom
divide(grid = grid,width = width,height = wall,fin = fin,xoff = xoff,yoff = yoff)
# i would expect the following to work when i just pass the grid
# that has been returned from the function call above (grid = grid)
# but that doesnt work
divide(grid = maze,height = height - wall,yoff = yoff + wall)
}
else
{
# Left and Right
divide(grid = grid,width = wall,height = height,yoff = yoff)
divide(grid = maze,width = width - wall,xoff = xoff + wall,yoff = yoff)
}
}
divide(maze,N,fin)
我的目标是通过仅将网格内部交给下一个递归步骤,而不是将其存储在全局对象“迷宫”中,来完成此工作。 还是这样一个问题:为什么返回函数不能将网格传递给下一个函数调用?
sessionInfo()
R version 4.0.2 (2020-06-22)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19041)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)