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

约翰·鲍姆

有一些有趣的逻辑,我正在尝试以最有效,最易读的方式进行编码。我将在下面布置场景(带有模拟/虚拟环境)

我有银行及其出纳员评论(1-5整数字段)的数据存储。柜员可以选择具有“客户选择优胜者”(CCW)字段。我的要求如下:为给定的银行向用户显示最多5个柜员:

  1. 如果柜员是CCW,请选择它。如果有多个柜员有CCW,请使用柜员审核打破平局
  2. 如果没有CCW,请选择评分最高的4位出纳员出纳员。

我必须对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.
    }
}

任何人都可以用一种更清晰,更有效的方式来帮助我写这篇文章吗?

谢谢!

詹姆斯·威洛(James Willow)

最好的解决方案是对List <Teller>进行排序

您将必须通过实现Comparable接口为Teller对象定义一个compare函数。

这样一来,您就可以恒定时间运行算法(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);
    //...
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章