为给定方案定义更有效的逻辑

时间:2015-08-31 14:20:54

标签: java logic

有一些有趣的逻辑,我试图以最有效和可读的方式进行编码。我将在下面列出一个scneario(使用模拟/虚拟上下文)

我有银行数据存储及其柜员评论(1-5 int field)。出纳员可以选择具有Customer Choice Winner(CCW)字段。我的要求如下,为给定银行最多选择5个柜员显示给用户:

  1. 如果出纳员是CCW,请选择它。如果多个柜员有CCW,请使用柜员评论打破关系
  2. 如果没有CCW,请选择最高4级出纳员审核的出纳员。
  3. 我必须为5家银行做上述事情。我得到的逻辑是有一个for循环遍历5个银行并在每个循环内,每个银行的所有出纳员5次(挑选5个出纳员)。在我看来,这是非常低效和不清楚的。这就是我的意思:

    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.
        }
    }
    

    任何人都可以用更清晰,更有效的方式帮我写这个吗?

    谢谢!

1 个答案:

答案 0 :(得分:1)

对此最好的解决方案是对List&lt; Teller&gt;

进行排序

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

这将让你在恒定时间内运行你的算法(O(25)因为5个银行的5个柜员,实际上是O(1))

以第一次排序为代价,即O(nlogn)

您的Teller类的示例代码:

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个出纳员。

示例:

//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);
    //...
}