java - 如何有效地限制 Java 中函数(任意时间算法)的时间?

标签 java algorithm search minimax

<分区>

我想用深度优先搜索来解决极小极大问题;然而,为了让我的算法能够完成并始终有一个解决方案,我使用迭代 DFS(所以找到一层深的所有节点,然后是两层,然后是三层)。我希望能够在经过一定时间后中断搜索,但是,除了将我的递归算法转换为带有堆栈的迭代算法并每次检查时间之外,我似乎找不到其他好方法循环(这似乎效率低下)或将结束时间传递给所有递归调用并在每次调用开始时检查(这似乎比迭代更低效,甚至更复杂)。

除了 Java 8 源代码之外,我不希望使用任何其他库。

伪代码:

function negamax(node, depth, α, β, color)
    if depth = 0 or node is a terminal node
        return color * the heuristic value of node
    bestValue := -∞
    childNodes := GenerateMoves(node)
    childNodes := OrderMoves(childNodes)
    foreach child in childNodes
        val := -negamax(child, depth - 1, -β, -α, -color)
        bestValue := max( bestValue, val )
        α := max( α, val )
        if α ≥ β
            break
    return bestValue

function search()
    depth := 0
    bestValue := null
    while (++depth > 0) // runs forever until interrupted
        bestValue := negamax( rootNode, depth, -∞, +∞, 1)
    return bestValue

function main()
    search();

最佳答案

您可以使用多线程概念。
例如:

Thread tempThread = new Thread("tempThread");
Thread originalThread = new Thread("DFSthread");
public void run() //run() of tempThread
{ 
 try{
      tempThread.sleep(1000); //you can add the limit you want here
      originalThread.stop();
}
catch(InterruptedException exc)
{
   System.out.println(exc);
}

希望对您有所帮助。

关于java - 如何有效地限制 Java 中函数(任意时间算法)的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28555582/

相关文章:

java - GLCanvas 上的模糊文字

java - HttpClient 4.3.1的org.apache.http.client.utils.URIBuilder中的 `removeQuery()`和 `clearParameters()`有什么区别?

python - 两个列表中元素之间的最小差和

c++ - 新的整数数组向右移动?

mysql - 如何一次搜索多个数据库?

Java:如何以更优雅的方式为 preparedStatement 插入多个值?

java - 构造函数的设计模式

algorithm - BTree-预定大小?

javascript - 按不包含字母开头搜索

c++ - 二分查找函数的问题