缺少x,没有默认值.调用R中函数中的函数



我正在编写一段代码,用YouTube上的一段视频解决数独难题,该视频通过Python编码了相同的算法。此代码需要的三个功能

  1. 找到一个空的正方形
  2. 在空正方形中插入一个数字
  3. 测试这个数字是否对解谜有效

这是对解算器使用回溯算法。

我在一起调用函数时遇到问题,出现错误:

Error in free_squ(x) : argument "x" is missing, with no default
In addition: Warning message:
In if (empty_sq == FALSE) { :
the condition has length > 1 and only the first element will be used
Called from: free_squ(x)

这很令人困惑,因为我只有在运行This代码时才能得到它。因此,我可以编写其他函数来调用各个函数,以分析插入到覆盖函数中的自变量:

function1(argument){
function2(argument){
function3(argument){
***DO STUFF***}}}

为什么以下代码的主函数中的函数不能识别参数?

sudoku_solve <- function(x){
empty_sq <- free_squ(x) # Define a new object to give coordinates of empty square
if(empty_sq == FALSE){ # If no empty square can be found
return(x) # Return the matrix
} else{
empty_sq <- empty_sq  # Pointless line kept for clarity
}
for(i in c(1:9)){ # Integers to insert into the found empty square
if(valid(x, i, empty_sq) == TRUE){ # can the intiger be placed in this square?
x[empty_sq[1], empty_sq[2]] = i # if i valid, insert into empty square
} 

if(sudoku_solve()){ # are all i's valid?
return(TRUE) # All i's valid
} else{
x[empty_sq[1], empty_sq[2]] = 0 # reset the initial try and try again with another
}
}
return(FALSE)
}

我已经将数独谜题命名为"谜题",并通过以下方式调用该函数:

sudoku_solve(puzzle)

我认为在下面的语句中,您没有向函数传递任何值,x也没有默认值。

if(sudoku_solve()){ # are all i's valid?
return(TRUE) # All i's valid
}

因此,尽管参数最初是传递的,但当函数在循环后再次调用时,它是在没有参数的情况下调用的。所以你在sudoku_solve((中传递给free_sq(x(,它会给出一个错误。

empty_sq <- free_squ(x)

确保将值传递给sudoku_solve,或者在sudoku_solve或free_squ类/函数中设置x的默认值。

最新更新