【发布时间】:2020-03-31 02:19:53
【问题描述】:
我正在编写代码来解决数独难题,使用从 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***}}}
为什么下面的代码主函数中的函数不能识别参数?
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)
【问题讨论】:
-
那么,你的“谜题”论点是什么样的?
-
这是一个 9 x 9 矩阵
标签: r function arguments sudoku