首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为给定场景定义更有效的逻辑

为给定场景定义更有效的逻辑
EN

Stack Overflow用户
提问于 2015-08-31 14:20:53
回答 1查看 71关注 0票数 2

有一些有趣的逻辑,我试图以最有效和最易读的方式编码。我将在下面列出一个模拟/虚拟的上下文。

我有一个银行及其出纳员评论的数据存储(1-5 int字段)。出纳员可以有一个客户选择优胜者(CCW)字段。我的要求如下所示,为一家银行向用户显示最多5名出纳员:

  1. 如果出纳员是特定常规武器,那就选择它。如果多个出纳员有CCW,请使用出纳员审查来打破联系。
  2. 当没有特定常规武器,选择出纳员与最大的4评级出纳员审查。

我必须为5家银行做上述工作。我得到的逻辑是有一个for循环来遍历5家银行,在每个循环中,对每个银行的所有出纳员进行5次检查(选择5位出纳员)。在我看来,这似乎是非常低效和不明确的。我的意思是:

代码语言:javascript
复制
foreach (Bank b : banks) {
    List<Tellers> tellers = b.getTellers();

    foreach (Teller t : tellers) {
        List<Reviews> reviews = t.getReviews();

        ...// get 4 reviews following the above logic.
    }
}

有人能帮我用一种更清晰、更有效的方式来写这个吗?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-31 14:44:17

对此最好的解决方案是对列表进行排序。

您必须通过实现可比较的接口为Teller对象定义一个比较函数。

这将允许您在固定时间内运行算法(O(25),因为5家银行有5名出纳员,实际上是O(1))。

以第一次排序为代价,这将是O(nlogn)

Teller类的示例代码:

代码语言:javascript
复制
public class Teller implements Comparable
{

    private boolean ccw = false;
    private int rating;

    public boolean hasCCW() { return ccw; }
    public int getRating() { return rating; }

    //... your code

    @Override
    public int compareTo(Object o) 
    {
        Teller that = (Teller)o;
        //if this has ccw and that doesn't, this < that
        if(this.hasCCW() && !that.hasCCW()) 
        {
            return -1;
        }
        //else if this does not have ccw, and that does, this > that
        else if(!this.hasCCW() && that.hasCCW())
        {
            return 1;
        }
        //else they both have ccw, so compare ratings
        else
        {
            return Integer.compare(this.getRating(), that.getRating());
        }
    }

}

然后,您的算法只需抓取每家银行的前5名出纳员。

示例:

代码语言:javascript
复制
//Sort the tellers:
//ideally, call this only once, and insert future Tellers in order (to maintain ordering)
for(Bank bank : banks)
{
    for(List<Teller> tellers : bank.getTellers())
    {
        Collections.sort(tellers);
    }
}

//then, to get your top tellers:
for(Bank bank : banks)
{
    Teller bestTeller = bank.getTeller(0);
    Teller secondBestTeller = bank.getTeller(1);
    //...
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32313484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档