[我正在使用从YouTube找到的video编写代码来解决数独难题,该代码已通过Python编码了相同的算法。此代码需要三个功能,以
这正在使用求解器的回溯算法。
我在收到错误的地方一起调用函数时遇到问题:
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)
这很令人困惑,因为我只有在运行此代码时才能得到它。因此,我可以编写其他函数来调用各个函数,以分析插入到上层函数中的参数:
function1(argument){
function2(argument){
function3(argument){
***DO STUFF***}}}
为什么下面的代码在main函数中的功能无法识别自变量?
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)
}
我将数独谜题命名为'puzzle',并通过以下方式调用该函数:
sudoku_solve(puzzle)
我认为在以下语句中,您没有将任何值传递给该函数,并且x也没有默认值。
if(sudoku_solve()){ # are all i's valid?
return(TRUE) # All i's valid
}
因此,当您将x传递到sudoku_solve()内的free_sq(x)时,会出现错误。
empty_sq <- free_squ(x)
请确保将值传递给sudoku_solve,或者在sudoku_solve或free_squ类/函数中设置x的默认值。