【问题标题】:Replacing recursion with while-loops and accumulators用while循环和累加器代替递归
【发布时间】:2013-11-11 15:47:04
【问题描述】:

我想计算高度并设置可能包含其他 JSplitPane 和其他组件的 JSplitPane 的 resizeWeight。这个概念现在看起来如下(警告:sn-p,不是功能齐全的代码片段;我只需要使用累加器使用 while 循环重写递归调用的指南,而不是功能齐全的解决方案代码)。

splitPane.setResizeWeight(calculateComponentHeight(splitPane.getTopComponent()) / calculateNewSplitPaneHeight(splitPane));
...
private double calculateNewSplitPaneHeight(JSplitPane sp) {
  return calculateComponentHeight(sp.getTopComponent()) + calculateComponentHeight(sp.getBottomComponent());
}

private double calculateComponentHeight(Component c) {
  if (c instanceof JSplitPane) {
    return calculateNewSplitPaneHeight((JSplitPane) c);
  }
  return (double) c.getHeight();
}

由于我可能不知道拆分窗格的嵌入程度,解决此类递归的实用方法是什么?

是的,我知道,splitPane.getPreferredSize().heightsplitPane.getTopComponent().getPreferredSize().height 无需任何递归调用即可给我所需的答案。这个问题只是为了在递归和循环上动脑筋。

【问题讨论】:

  • 出于兴趣,您为什么要进行此更改?
  • 因为我发现将递归转换为循环很有趣。然而,我发现自己是一个有趣的问题,它看起来像一个双重递归,它让我一直在思考如何解决这样的递归。我想教我的大脑以这种方式思考。

标签: java swing recursion


【解决方案1】:

您可以使用堆栈模拟递归:How can you emulate recursion with a stack?

我曾经尝试过模拟一个简单的类斐波那契递归:

f(n) = f(n-1) + f(n-2) + array[n]

结果为@​​987654322@,并根据链接答案中的说明编写。我应该承认这是一项比我最初想象的更复杂的任务。

【讨论】:

  • 鉴于嵌入的拆分窗格足够大,堆栈不会过载吗?这就是为什么我一直在考虑使用累加器的方法。
  • 这里的堆栈是模拟的——它是一个ArrayList,它存储在堆中。我很确定您可能会离开递归,因为在您的示例中您实际上不会到达堆栈底部,这可能是具有默认堆栈大小的约 1000 个嵌入式窗格。
猜你喜欢
  • 2021-05-03
  • 2014-08-05
  • 2013-08-12
  • 1970-01-01
  • 2014-10-20
  • 2012-05-26
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
相关资源
最近更新 更多