algorithm - 实现此算法的最佳方法是什么?

标签 algorithm optimization

编写如下算法的最佳方法是什么:

if (a) {
  doA();
  done();
}
else if (b) {
  doB();
  done();
}
else if (c) {
  doC();
  done();
}

我想到的另一种方法:

done = true;
if (a) {
  doA();
}
else if (b) {
  doB();
}
else if (c) {
  doC();
}
else {
  done = false;
}
if (done) {
  done();
}

哪个更好?还有其他最佳方法吗?

最佳答案

在没有任何上下文的情况下,对我来说最自然的方式是:

bool do_it(int condition)
{
    switch (condition)
    {
        case a: doA(); return true;
        case b: doB(); return true;
        case c: doC(); return true;
        default: return false;
    }
}

// ...

if (do_it) done();

因为它抽象了“如果这一切都成功了,那么就调用done()”的逻辑。

但是还有许多其他方法可以做到这一点。特别是,如果 future 条件的数量可能会增加,我根本不会这样做。

关于algorithm - 实现此算法的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5567235/

相关文章:

mysql - 在过滤不活跃用户(即没有任何交易)后,从拥有约 1000 万用户和交易的系统中获取旧的用户余额

mysql - 在集合 (val11,val21,val31),...,(val11,val21,val31) 中选择 (field1, field2, field3) 的行

c# - 我怎样才能优化这个递归方法

list - 稍微改变种子时稍微改变随机列表随机播放的输出

algorithm - 使用遗传算法选择稀疏参数

javascript - 给定一组数字问题的可能三 Angular 形的数量

c++ - 比较不同版本库性能的最佳方法

c++ - 哪个(如果有的话)C++ 编译器进行尾递归优化?

c - QuickSort 中的分割

算法树或植物生长背后的算法